Search code examples
rubyruby-hash

how to access value from hash based on key value


I have following hash

hash = {
   "some value": "abc",
   "other value": "dcd"
}

The key value is coming from an object Test and I can access it as Test.key

I am trying to access hash value from the key which is coming from Test.key. I tried to access the key value from hash hash[:Test.key] but that returns NoMethodError Exception: undefined method 'key' for :activity:Symbol

How could i access the hash value?


Solution

  • Ruby uses Object#eql? method to compare hash keys. If Test.key is a String and the hash key is a Symbol, you need to convert it to a Symbol.

    Instead of using hash[Test.key], use hash[Test.key.to_sym].

    See also Object#eql? and Hash.