使用sample
从数组中选择随机方法,然后使用send
:
# Make a few methods
def a; 1; end
def b; 2; end
def c; 3; end
def d; 4; end
def e; 5; end
# Put their names in an array
methods = %i[a b c d e]
# Call a random one
send methods.sample #=> 4
send methods.sample #=> 1
send methods.sample #=> 3