执行随机方法 [英] Executing a random method

查看:84
本文介绍了执行随机方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为执行随机方法制定逻辑.例如,假设我有10种方法,我需要随机运行其中一种方法.

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.

主要方法将驻留在我的Rails 3.2应用程序的ActionController中,其中将包含逻辑和10个方法.

The main method will reside in the ActionController of my Rails 3.2 app which will have the logic and the 10 methods inside.

推荐答案

使用 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

这篇关于执行随机方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆