instance_eval
[1, 2, 3, 4].instance_eval { at(rand(size)) }
, , Array#at , Array#sample .
[1,2,3,4].sample
#=> 3
If you don’t want to use instance_eval(or any form eval), then you can add the method to the class Arrayby patch of monkeys - generally speaking, I'm not sure if he is wise Idea for patch of monkey, though
class Array
def random_index
rand(size)
end
end
["a","b","c","d"].random_index
source
share