【发布时间】: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