如果我有以下ruby哈希:
environments = {
'testing' => '11.22.33.44',
'production' => '55.66.77.88'
}
Run Code Online (Sandbox Code Playgroud)
我如何访问上述哈希的部分内容?下面举例说明我想要实现的目标.
current_environment = 'testing'
"rsync -ar root@#{environments[#{testing}]}:/htdocs/"
Run Code Online (Sandbox Code Playgroud)
看起来你想要exec最后一行,因为它显然是一个shell命令而不是Ruby代码.你不需要插值两次; 曾经做过:
exec("rsync -ar root@#{environments['testing']}:/htdocs/")
Run Code Online (Sandbox Code Playgroud)
或者,使用变量:
exec("rsync -ar root@#{environments[current_environment]}:/htdocs/")
Run Code Online (Sandbox Code Playgroud)
请注意,更多Ruby方法是使用Symbols而不是Strings作为键:
environments = {
:testing => '11.22.33.44',
:production => '55.66.77.88'
}
current_environment = :testing
exec("rsync -ar root@#{environments[current_environment]}:/htdocs/")
Run Code Online (Sandbox Code Playgroud)
您可以使用括号:
environments = {
'testing' => '11.22.33.44',
'production' => '55.66.77.88'
}
myString = 'testing'
environments[myString] # => '11.22.33.44'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11041 次 |
| 最近记录: |