我有一些看起来像这样的变量:
top_script_path = "path/to/top"
bottom_script_path = "path/to/bottom"
script_names = ["top", "bottom"]
我想调用每个脚本
`#{top_script_path} "top"`
puts "top script successful"
`#{bottom_script_path} "bottom"`
puts "bottom script successful"
然而,对于我来说,这个解决方案对我来说感觉不够干净。我希望能够做一些像这样的事情
script_names.each do |name|
`#{#{name}_script_path} #{name}`
puts "#{name} script successful"
end
显然,如上所述,将{{expression}放在#{表达式}中是不可能的,但有没有其他方法可以用循环来干掉这段代码?
答案 0 :(得分:2)
script_names.each do |name|
`#{eval("#{name}_script_path")} #{name}`
puts "#{name} script successful"
end
答案 1 :(得分:2)
使用哈希:
script_paths = {
:top => 'path/to/top',
:bottom => 'path/to/bottom',
}
script_names = script_paths.keys
script_names.each do |name|
# `...`
puts "#{script_paths[name]} #{name}"
end
执行命令
$ ruby qq.rb
path/to/top top
path/to/bottom bottom
答案 2 :(得分:0)
我会将变量重构为一个结构,例如:
scripts = {
'top' => 'path/to/top',
'bottom' => 'path/to/bottom'
}
scripts.each do |name, path|
`#{path} #{name}`
puts "#{name} script successful"
end
如果您正在编写某种构建脚本,请考虑使用Rake。