# arguments to rand

hi -

can someone help with suggesting what is wrong below? i am trying to
add a simple method to array#random

but get the wrong number of args error…
have tried lots of variations!

class Array
def random
n = rand(self.size.to_i)
return self[n]
end
end
=> nil

[1, 2, 3].random
ArgumentError: wrong number of arguments (1 for 0)
from (irb):14:in rand' from (irb):14:inrandom’
from (irb):18

rand(3)
=> 1

rand(3)
=> 1

rand(3)
=> 2

tx

/dc

Alle Tuesday 26 February 2008, d c ha scritto:

n = rand(self.size.to_i)

from (irb):14:in `random’

rand(3)

=> 2

tx

/dc

It works for me. By the way, you don’t need the to_i in the call to
rand:
Array#size is already and integer.

Stefano

On Tue, Feb 26, 2008 at 3:14 PM, d c [email protected] wrote:

n = rand(self.size.to_i)

=> 1

Works for me.

On 26/02/2008, d c [email protected] wrote:

n = rand(self.size.to_i)

You are probably calling Array#rand as defined by Rails. If so, it
does what your Array#random is supposed to do and you can use it
directly. Otherwise you can call Kernel.rand instead of just rand.

Peter

d c wrote:

can someone help with suggesting what is wrong below?

You’re monkey patching a built-in class. :wink:

Best regards,

Jari W.

i am trying to

David C. wrote:

class Array
def random
n = rand(self.size.to_i)
return self[n]
end
end
=> nil

[1, 2, 3].random
ArgumentError: wrong number of arguments (1 for 0)
from (irb):14:in `rand’

Did you by any chance alias random to rand in Array? If so then that
would be the reason.
Anyway, maybe you can use this one, it’s what I use for Array#random:

class Array

Get a random element of this array

With an argument it gets you n elements without any index used more

than once
def random(n=nil)
unless n then
at(rand(length))
else
raise ArgumentError unless Integer === n and n.between?(0,length)
ary = dup
l = length
n.times { |i|
r = rand(l-i)+i
ary[r], ary[i] = ary[i], ary[r]
}
ary.first(n)
end
end
end

On Feb 26, 8:52 am, Calamitas [email protected] wrote:

class Array
def random
n = rand(self.size.to_i)

You are probably calling Array#rand as defined by Rails. If so, it
does what your Array#random is supposed to do and you can use it
directly. Otherwise you can call Kernel.rand instead of just rand.

Peter

This is what I was going to bring up. I’d also like to add that it was
a wonderful decision on Norbert Crombach’s part to name the method
Array#rand rather than Array#random so that confusion and/or annoyance
would set in were one to attempt to add another method to Array that
attempts to use random numbers. Oh, also the Rails core team in
general for not bringing this up and accepting the patch without a
comment.