Accessing a Ruby hash with a variable as the key

后端 未结 2 1393
忘了有多久
忘了有多久 2021-01-17 12:10

If I had the following ruby hash:

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

How wou

相关标签:
2条回答
  • 2021-01-17 12:23

    You would use brackets:

    environments = {
       'testing' =>  '11.22.33.44',
       'production' => '55.66.77.88'
    }
    myString = 'testing'
    environments[myString] # => '11.22.33.44'
    
    0 讨论(0)
  • 2021-01-17 12:32

    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/")
    

    Or, using the variable:

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

    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/")
    
    0 讨论(0)
提交回复
热议问题