问题
I am trying to make a logic for executing a random method. Let's say for example I have 10 methods, I need to run one of them selected at random.
The main method will reside in the ActionController of my Rails 3.2 app which will have the logic and the 10 methods inside.
回答1:
Pick a random method from an array using sample, then use 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
来源:https://stackoverflow.com/questions/19555919/executing-a-random-method