【问题标题】:Ruby - any method to do a string substitution for a definition?Ruby - 有什么方法可以对定义进行字符串替换?
【发布时间】:2015-11-16 13:03:51
【问题描述】:

喂! 我有以下(狙击脚本)。我有一个具有多个定义的类,我想遍历这些定义,直到某些定义返回 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)

【问题讨论】:

标签: ruby


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    相关资源
    最近更新 更多