使用变量作为键访问Ruby哈希表

13
如果我有以下的 Ruby 哈希表:
environments = {
   'testing' =>  '11.22.33.44',
   'production' => '55.66.77.88'
}

我如何访问上述哈希表的部分内容?下面是我想要实现的一个示例。

current_environment = 'testing'
"rsync -ar root@#{environments[#{testing}]}:/htdocs/"
2个回答

8

看起来你想要执行最后一行,因为它显然是一个Shell命令而不是Ruby代码。你不需要两次插值; 一次就够了:

exec("rsync -ar root@#{environments['testing']}:/htdocs/")

或者,使用变量:

或者,使用变量:

exec("rsync -ar root@#{environments[current_environment]}:/htdocs/")

请注意,更符合Ruby的方法是使用符号而不是字符串作为键:
environments = {
   :testing =>  '11.22.33.44',
   :production => '55.66.77.88'
}

current_environment = :testing
exec("rsync -ar root@#{environments[current_environment]}:/htdocs/")

5
您需要使用括号: ```

您需要使用括号:

```
environments = {
   'testing' =>  '11.22.33.44',
   'production' => '55.66.77.88'
}
myString = 'testing'
environments[myString] # => '11.22.33.44'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接