ħ! 我有以下(sniped脚本)。我有一个有多个定义的类,我想迭代这些定义,直到某个定义返回true,所以我想将它们放入一个数组并进行迭代,我的问题是当我想通过它的类来替换时我访问该定义定义的名称,所以我可以在while循环中使用它我不能这样做因为它返回我的错误。知道怎么做吗?
#...
class FetchHash
def get_img_eight(something)
#...
end
def get_img_seven(someting)
#...
end
def get_img_six(something)
#...
end
def get_img_five(something)
#...
end
end
get_cmds = [ "get_img_eight", "get_img_seven", "get_img_six", "get_img_five" ]
fetchme = FetchHash.new
for get_cmd in (get_cmds)
while my_ret_hash.nil? do
mynotworkingcmd = "fetchme.#{get_cmd}"
my_ret_hash = mynotworkingcmd(something)
break if my_ret_hash.nil?
end
end
#...
错误:
./test:85:in `block in <main>': undefined method `mynotworkingcmd' for main:Object (NoMethodError)
from ./test.rb:82:in `each'
from ./test:82:in `<main>'
此sniped中的行85
对应于my_ret_hash = mynotworkingcmd(something)
答案 0 :(得分:1)
一种方法是使用public_send
,如下所示:
get_cmds = [ "get_img_eight", "get_img_seven", "get_img_six", "get_img_five" ]
fetchme = FetchHash.new
for get_cmd in (get_cmds)
while my_ret_hash.nil? do
my_ret_hash = fetchme.public_send(cmd.to_sym, something)
break if my_ret_hash.nil?
end
end