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