Forum: Ruby on Rails Rails console

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel (Guest)
on 2008-10-30 17:23
(Received via mailing list)
I tried to create an addition to Enumerable called choose_randomly
that picks a random element from the Enumerable object. However when I
define it and execute the code rand complains about the wrong number
of arguments. Below is a capture of the ./script/console session.

farrel@nicodemus ~/Work/GreenGreen/Code/green_green_client_application
$ ./script/console
Loading development environment (Rails 2.1.2)
>> [1,2,3].choose_randomly
NoMethodError: undefined method `choose_randomly' for [1, 2, 3]:Array
  from (irb):1
>> module Enumerable
>>   def choose_randomly
>>     array_of_self = Array( self )
>>     index = rand( array_of_self.size )
>>     array_of_self[ index ]
>>   end
>> end
=> nil
>> [1,2,3].choose_randomly
ArgumentError: wrong number of arguments (1 for 0)
  from (irb):5:in `rand'
  from (irb):5:in `choose_randomly'
  from (irb):9
>> [1,2,3][ rand( [1,2,3].size )]
=> 1

As you can see if I execute the code myself it seems to work. If I
copy that same code into irb it works perfectly.

Any ideas?

Farrel
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2008-10-30 18:06
(Received via mailing list)
On 30 Oct 2008, at 16:22, Farrel wrote:
>
>
> As you can see if I execute the code myself it seems to work. If I
> copy that same code into irb it works perfectly.
>
You're calling Array#rand (a private method Array defines), whereas
you want to call Kernel#rand. Replace rand with Kernel.rand and you
should be ok

Fred
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel (Guest)
on 2008-10-30 19:42
(Received via mailing list)
On Oct 30, 7:05 pm, Frederick Cheung <frederick.che...@gmail.com>
wrote:
> You're calling Array#rand (a private method Array defines), whereas
> you want to call Kernel#rand. Replace rand with Kernel.rand and you
> should be ok

That was it. Thanks for the tip. I didn't know Rails added in it's own
rand method into Array.

Farrel
This topic is locked and can not be replied to.