Emil K. wrote:
I have bould an array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and want to get a
random element from it. If i use array.rand the controller returns this
error
private method `rand' called for [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:Array
Why is the rand private, and cannot be accesed naturally on all and/or
any array element?
#rand is actually defined as a global function. It doesn’t take a
receiver in the core code.
To get a random element of an array:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a[rand(a.length)]
If you want to apply it as a method, you can define something like:
class Array
def rand
self[super(self.length)]
end
end
or:
class Integer
def rand
super self
end
end
class Array
def rand
self[self.length.rand]
end
end