gpt4 book ai didi

ruby - 访问以变量为键的 Ruby 散列

转载 作者:数据小太阳 更新时间:2023-10-29 06:50:08 26 4
gpt4 key购买 nike

如果我有以下 ruby​​ 哈希:

environments = {
'testing' => '11.22.33.44',
'production' => '55.66.77.88'
}

我将如何访问上述散列的部分内容?下面是关于我要实现的目标的示例。

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

最佳答案

您似乎想要 exec 最后一行,因为它显然是一个 shell 命令而不是 Ruby 代码。您不需要插值两次;一次就可以:

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

或者,使用变量:

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

请注意,更多的 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/")

关于ruby - 访问以变量为键的 Ruby 散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16289373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com