views:

132

answers:

1

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?

+6  A: 

That's not valid Ruby syntax. You want:

@user.badges.any? { |b| b[:id] == 1 }
Bob Aman
Thanks bob! I guess it was wishful thinking that I could treat any hash as an array.
Joseph Silvashy
Well, the syntax you used was wrong for two reasons. First `(:id => 1)` does not resolve to an expression (or anything else for that matter). And second, you called `Array#include?`, rather than `Hash#include?`. And finally, `Hash#include?` is merely an alias for `Hash#has_key?`
Bob Aman
Actually, the (:id => 1) part is syntactically valid. Ruby recognizes this as a shortcut for ({:id => 1}), as you can see if you do `badges.include?(:id => 1, :name => 'blahh', :description => 'blah blah blah')`, which will return `true`.So the problem here, more precisely, was that `Array#include?` only does exact matching of elements, and you were trying to do a partial match. Thus `any?`, because you get to pass it a block instead of just a value.If you needed to return the matching hash, instead of just checking if one exists, you'd replace the `any?` with `find`.
glenn mcdonald
I was thinking that he was trying to do: `{:id => 1, :name => 'blahh', :description => 'blah blah blah'}.include?(:id => 1)`, and didn't notice that the syntax was still valid despite the assumed intent. You're right: if a `:id => 1` appears as an argument to a method, it's assembled into a `Hash` and passed in as the last parameter. However, just to be clear, this is still not valid syntax outside of a method call.
Bob Aman
`any?` was the route I went with, thanks for the help you guys!
Joseph Silvashy