Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using `include?` in ruby to check if something is in a hash

I'm aware of how include? works, however not really clear using it with multidimensional array, or a hash (is this possible with a hash?)

For example, given I have a hash that looks like:

@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 the id of 1 in it like this?

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

It doesn’t seem to work, how I can I write this method properly?

like image 383
JP Silvashy Avatar asked Nov 15 '09 09:11

JP Silvashy


1 Answers

That's not valid Ruby syntax. You want:

@user.badges.any? { |b| b[:id] == 1 }
like image 172
Bob Aman Avatar answered Sep 20 '22 17:09

Bob Aman