Array.rand fails - Why?

Hey guys.

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

[code] private method `rand' called for [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:Array [/code]

Why is the rand private, and cannot be accesed naturally on all and/or any array element?

Hey guys.

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

[code] private method `rand' called for [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:Array [/code]

Why is the rand private, and cannot be accesed naturally on all and/or any array element?

It's private in a 'normal' array. My guess is that it's because that
rand method isn't the rand method you think it is (ie it doesn't
return a random element from it), so making it public would invite
confusion. The version of activesupport in rails 2 adds a public rand
method that does do what you want. It's nothing fancy though, just
some_array[Kernel.rand(some_array.length)]

Fred

Emil Kampp 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

[code] private method `rand' called for [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:Array [/code]

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