Let\'s say I want to access an element of an array at a random index this way:
[1, 2, 3, 4].at(rand(4))
Is there a way to pass the size of
You can use instance_eval
to execute ruby code with the binding of the array variable
[1, 2, 3, 4].instance_eval { at(rand(size)) }
Assuming you are interested in a random element as Array#at
returns an element at given index, you can use Array#sample
to pick a random element from an array.
[1,2,3,4].sample
#=> 3
If you do not want to use instance_eval
(or any form of eval
), then, you can add a method to Array
class by monkey patching - generally speaking, I am not sure whether it's a wise idea to monkey patch though
class Array
def random_index
rand(size)
end
end
["a","b","c","d"].random_index
#=> 2