Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4619

In Ruby, how do I find a value in an array of hashes?

$
0
0

I am trying to get a value in an array of hashes in Ruby. Given the following information below:

  # array_of_hash_objects will look something like this:  # [  #   { name: 'Ruby', is_my_favorite?: true },  #   { name: 'JavaScript', is_my_favorite?: false },  #   { name: 'HTML', is_my_favorite?: false }  # ]

I simply want to return the name where the value is true. My thoughts were to use the collect method in an expression like this: array_of_hash_objects.collect { |name, fave| if fave[:is_my_favorite?] == true }.compact

However, when I try this in irb, I get the following error:

NoMethodError:undefined method `[]' for nil

I cannot for the life of me figure out what I've done wrong.

I have tried using both the collect and select methods with the same result above.


Viewing all articles
Browse latest Browse all 4619

Trending Articles