使用变量作为键访问 Ruby 哈希
问题描述:
如果我有以下 ruby 哈希值:
If I had the following ruby hash:
environments = {
'testing' => '11.22.33.44',
'production' => '55.66.77.88'
}
我将如何访问上述散列的部分内容?下面是我想要实现的目标的示例.
How would I access parts of the above hash? An example below as to what I am trying to achieve.
current_environment = 'testing'
"rsync -ar root@#{environments[#{testing}]}:/htdocs/"
答
看起来您想要 exec
最后一行,因为它显然是一个 shell 命令而不是 Ruby 代码.你不需要插值两次;一次就可以:
It looks like you want to exec
that last line, as it's obviously a shell command rather than Ruby code. You don't need to interpolate twice; once will do:
exec("rsync -ar root@#{environments['testing']}:/htdocs/")
或者,使用变量:
exec("rsync -ar root@#{environments[current_environment]}:/htdocs/")
请注意,更 Ruby 的方式是使用 Symbols 而不是 Strings 作为键:
Note that the more Ruby way is to use Symbols rather than Strings as the keys:
environments = {
:testing => '11.22.33.44',
:production => '55.66.77.88'
}
current_environment = :testing
exec("rsync -ar root@#{environments[current_environment]}:/htdocs/")