TIPA Sylvaire-Kevin
TIPA Sylvaire-Kevin

Reputation: 123

ruby acces hash with variable as key

I have a simple (I think) question about hash access. I have the following hash (getting form yml file)

 {
   "all"=>   {
      "children"=> {
         "TSL-PCM-126"=>    {
            "children"=>  {
               "my_host-TSL-PCM-126"=> {
                  "hosts"=>   {
                     "TSF-W01"=> {
                        "ip"=>"192.168.0.201"
                     }
                  }
               }
            }
          }
      }
   }
}

I store my hostname as variable

my_pc="#{`hostname`}" ==> my_pc="TSL-PCM-126"

I want to access to the right value but using my_pc variable as key ...

(inventory = Yaml Load of my file)

puts inventory["all"]["children"] ==> Work
puts inventory["all"]["children"]["TSL-PCM-126"] ==> Work 
puts inventory["all"]["children"]["#{my_pc}"] ==> NOK :( 

Upvotes: 0

Views: 62

Answers (2)

ReggieB
ReggieB

Reputation: 8212

When I enter

`hostname`

On my PC I get the response "dell\n". The key thing here is the \n at the end. That's an end of line character. So I wonder whether on your PC it is actually returning my_pc="TSL-PCM-126\n". The end of line won't be obvious if you are only using puts to examine it. As "TSL-PCM-126\n" != "TSL-PCM-126" you don't get a key match.

The string method chomp will remove the \n character, and give you the match you are after. So:

puts inventory["all"]["children"][`hostname`.chomp]

Upvotes: 1

Marcin Kołodziej
Marcin Kołodziej

Reputation: 5313

After OP's edit, use

my_pc = `hostname`.strip

to avoid newline in your string.

This does work as expected,

> my_pc
 => "TSL-PCM-126" 
> puts inventory["all"]["children"]["#{my_pc}"]
{"children"=>{"my_host-TSL-PCM-126"=>{"hosts"=>{"TSF-W01"=>{"ip"=>"192.168.0.201"}}

You do not need string interpolation though:

> inventory["all"]["children"][my_pc]
=> {"children"=>{"my_host-TSL-PCM-126"=>{"hosts"=>{"TSF-W01"=>{"ip"=>"192.168.0.201"}}}}}

You either have a typo in your variable/hash or you're trying to assign the return value of puts, which is nil.

Upvotes: 1

Related Questions