How to access a symbol hash key using a variable in Ruby

20,953

Solution 1

You want to convert your string to a symbol first:

another_family[somevar.to_sym]

If you want to not have to worry about if your hash is symbol or string, simply convert it to symbolized keys

see: How do I convert a Ruby hash so that all of its keys are symbols?

Solution 2

You can use the Active Support gem to get access to the with_indifferent_access method:

require 'active_support/core_ext/hash/indifferent_access'
> hash = { somekey: 'somevalue' }.with_indifferent_access
 => {"somekey"=>"somevalue"}
> hash[:somekey]
 => "somevalue"
> hash['somekey']
=> "somevalue"

Solution 3

Since your keys are symbols, use symbols as keys.

> hash = { :husband => 'Homer', :wife => 'Marge' }
 => {:husband=>"Homer", :wife=>"Marge"}
> key_variable = :husband
 => :husband
> hash[key_variable]
 => "Homer"
Share:
20,953

Related videos on Youtube

Leonard
Author by

Leonard

Software engineer and Psychotherapist. Unix, C and RoR in the programming world, Gestalt, Somatic Experiencing and Dream Interpretation in the psychotherapy world.

Updated on April 15, 2020

Comments

  • Leonard
    Leonard about 4 years

    I have an array of hashes to write a generic checker for, so I want to pass in the name of a key to be checked. The hash was defined with keys with symbols (colon prefixes). I can't figure out how to use the variable as a key properly. Even though the key exists in the hash, using the variable to access it results in nil.

    In IRB I do this:

    >> family = { 'husband' => "Homer", 'wife' => "Marge" }
    => {"husband"=>"Homer", "wife"=>"Marge"}
    >> somevar = "husband"
    => "husband"
    >> family[somevar]
    => "Homer"
    >> another_family  = { :husband => "Fred", :wife => "Wilma" }
    => {:husband=>"Fred", :wife=>"Wilma"}
    >> another_family[somevar]
    => nil
    >>
    

    How do I access the hash key through a variable? Perhaps another way to ask is, how do I coerce the variable to a symbol?

    • Cary Swoveland
      Cary Swoveland almost 10 years
      "husband".to_sym => :husband.
    • Ken Ratanachai S.
      Ken Ratanachai S. over 5 years
      @CarySwoveland Watch out for NoMethodError: undefined method `to_sym' for nil:NilClass when var is nil
  • PJP
    PJP almost 10 years
    This uses ActiveSupport Core Extensions, which is the proper way to cherry-pick specific extensions.
  • Leonard
    Leonard almost 10 years
    This might work in some circumstances, but in my case I'm passing them in as parameters, and Trollop (argument parsing gem) won't accept a symbol as a default value.
  • Ken Ratanachai S.
    Ken Ratanachai S. over 5 years
    Do watch out for nil somevar, though.