使用变量作为键访问 Ruby 哈希 [英] Accessing a Ruby hash with a variable as the key

查看:40
本文介绍了使用变量作为键访问 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/")

这篇关于使用变量作为键访问 Ruby 哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆