H!我有以下(狙击脚本(。我有一个有多个定义的类,我想迭代这些定义,直到某个定义返回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>'
此狙击中的线85
对应于my_ret_hash = mynotworkingcmd(something)
这样做的一种方法是使用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