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

编程入门 行业动态 更新时间:2024-10-26 22:25:16
本文介绍了使用变量作为键访问 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 哈希

本文发布于:2023-11-23 17:36:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622316.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   Ruby   哈希

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!