Executing a random method [closed]

穿精又带淫゛_ 提交于 2019-12-20 06:27:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!