执行随机方法
我正在尝试为执行随机方法制作逻辑。 比方说,我有10个方法,我需要随机选择其中一个。
main方法将驻留在我的Rails 3.2应用程序的ActionController中,该应用程序将包含逻辑和10个方法。
使用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[abcde] # Call a random one send methods.sample #=> 4 send methods.sample #=> 1 send methods.sample #=> 3