在这种情况下是否有必要使用eval?

时间:2013-09-03 11:28:48

标签: ruby metaprogramming

在Paolo Perrotta编写的书 Metaprogramming Ruby :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。这只是一种编程风格试图让一切都使用字符串替换吗?

1 个答案:

答案 0 :(得分:0)

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
相关问题