Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用变量作为键访问Ruby哈希_Ruby - Fatal编程技术网

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

使用变量作为键访问Ruby哈希,ruby,Ruby,如果我有以下ruby哈希: environments = { 'testing' => '11.22.33.44', 'production' => '55.66.77.88' } 我如何访问上述散列的部分内容?下面举一个例子来说明我正在努力实现的目标 current_environment = 'testing' "rsync -ar root@#{environments[#{testing}]}:/htdocs/" 您可以使用括号: environments

如果我有以下ruby哈希:

environments = {
   'testing' =>  '11.22.33.44',
   'production' => '55.66.77.88'
}
我如何访问上述散列的部分内容?下面举一个例子来说明我正在努力实现的目标

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

您可以使用括号:

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

看起来您想要执行最后一行,因为这显然是一个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/")
非常好:)谢谢你的回答。