0

在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这种方式。这只是一种试图让一切都使用字符串替换的编程风格吗?

4

1 回答 1

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
于 2013-09-03T11:42:27.443 回答