如何根據(jù)方法的名稱動(dòng)態(tài)調(diào)用方法?當(dāng)方法的名稱包含在字符串變量中時(shí),如何動(dòng)態(tài)調(diào)用它?例如:class MyClass
def foo; end
def bar; endendobj = MyClass.new
str = get_data_from_user # e.g. `gets`, `params`, DB access, etc.str #=> "foo"# somehow call `foo` on `obj` using the value in `str`.我該怎么做?這樣做會(huì)帶來(lái)安全風(fēng)險(xiǎn)嗎?
3 回答

泛舟湖上清波郎朗
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
public_send
:
method_name = 'foobar'obj.public_send(method_name) if obj.respond_to? method_name
send
public_send
.
method_name
if obj.respond_to?(method_name) && %w[foo bar].include?(method_name) obj.send(method_name)end
- 3 回答
- 0 關(guān)注
- 804 瀏覽
添加回答
舉報(bào)
0/150
提交
取消