我正在尝试制定执行随机方法的逻辑。比方说,我有 10 个方法,我需要运行随机选择的其中一个。
main 方法将驻留在我的 Rails 3.2 应用程序的 ActionController 中,其中包含逻辑和 10 个方法。
使用以下命令从数组中选择一个随机方法sample http://ruby-doc.org/core-2.0.0/Array.html#method-i-sample,然后使用send http://ruby-doc.org/core-2.0.0/Object.html#method-i-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