Using `include? 'in ruby ​​to check something in a hash

I know how it works include?, but it's not entirely clear using it with a multidimensional array or hash (is this possible with a hash?)

For example, if I have a hash that looks like this:

@user.badges => [{:id => 1, :name => 'blahh', :description => 'blah blah blah'}, {:id => 2, :name => 'blahh', :description => 'blah blah blah'}]

Can I see if it has an object with id 1 in it?

if @user.badges.include?(:id => 1)
  # do something
end

It doesn't seem to work, how can I write this method correctly?

+5
source share
1 answer

This is not valid Ruby syntax. Do you want to:

@user.badges.any? { |b| b[:id] == 1 }
+13
source

All Articles