Accessing a Ruby hash with a variable as the key

后端 未结 2 1410
忘了有多久
忘了有多久 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: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/")
    

提交回复
热议问题