jose1221
jose1221

Reputation: 263

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?

Upvotes: 1

Views: 113

Answers (1)

justapilgrim
justapilgrim

Reputation: 6882

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.

Upvotes: 1

Related Questions