【问题标题】:Is it necessary to use eval in this case?在这种情况下是否有必要使用 eval ?
【发布时间】:2013-09-03 11:28:47
【问题描述】:

Metaprogramming Ruby一书中,Paolo Perrotta写的164,有一个使用eval的例子。

map = { "update" => "deploy:update" ,
        "restart" => "deploy:restart" ,
        "cleanup" => "deploy:cleanup" ,
# ...
}
map.each do |old, new|
  # ...
  eval "task(#{old.inspect}) do
    warn \"[DEPRECATED] `#{old}' is deprecated. Use `#{new}' instead.\"
    find_and_execute_task(#{new.inspect})
  end"
end

有必要使用eval吗?我可以编写如下代码:

map = { "update" => "deploy:update" ,
        "restart" => "deploy:restart" ,
        "cleanup" => "deploy:cleanup" ,
        # ...
        }
map.each do |old, new|
    task(old.inspect) do
        warn \"[DEPRECATED] `#{old}' is deprecated. Use `#{new}' instead.\"
        find_and_execute_task(new.inspect)
    end
end

我认为没有必要这样使用eval。这只是一种试图让一切都使用字符串替换的编程风格吗?

【问题讨论】:

  • 如果你能躲开eval,那就去做吧。确实,这里似乎没有必要。

标签: ruby metaprogramming


【解决方案1】:

eval 不是必需的,但您的代码也不起作用。它不是有效的 Ruby 代码。应该是

map.each do |old, new|
  task(old) do
    warn "[DEPRECATED] `#{old}' is deprecated. Use `#{new}' instead."
    find_and_execute_task(new)
  end
end

【讨论】:

    猜你喜欢
    • 2017-08-31
    • 1970-01-01
    • 2010-10-31
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    相关资源
    最近更新 更多