Check if array content an object using include

38 views
Skip to first unread message

Jean

unread,
Jan 5, 2013, 2:49:33 PM1/5/13
to rubyonra...@googlegroups.com

I have the following array on my rails console:

u.favorites

[#<Favorite id: 20, candidate_id: 6, ...>, #<Favorite id: 21, candidate_id: 7,..">, #<Favorite id: 22, candidate_id: 8, ...">, #<Favorite id: 23, candidate_id: 9, ...">, #<Favorite id: 24, candidate_id: 10, ...">]

As you can see, I have candidate_id:6, candidate_id:7, candidate_id:8, candidate_id:9, candidate_id:10. But if I try this:

u.favorites.include?(:candidate_id => 5) o canidate 6, 7, 8, 9 or 10 I get false.

What I'm doing wrong?

Thanks in advance for your help.

Hassan Schroeder

unread,
Jan 5, 2013, 3:31:16 PM1/5/13
to rubyonra...@googlegroups.com
On Sat, Jan 5, 2013 at 11:49 AM, Jean <joso...@gmail.com> wrote:

> [#<Favorite id: 20, candidate_id: 6, ...>, #<Favorite id: 21, candidate_id:
> 7,..">, #<Favorite id: 22, candidate_id: 8, ...">, #<Favorite id: 23,
> candidate_id: 9, ...">, #<Favorite id: 24, candidate_id: 10, ...">]
>
> As you can see, I have candidate_id:6, candidate_id:7, candidate_id:8,
> candidate_id:9, candidate_id:10. But if I try this:
>
> u.favorites.include?(:candidate_id => 5) o canidate 6, 7, 8, 9 or 10 I get
> false.
>
> What I'm doing wrong?

You're trying to compare a Favorite object to a symbol.

So either pass a Favorite object as an argument to `include?` for
comparison or use something like `Enumerable#find` to select on
your desired attribute (e.g. candidate_id).

You might want to spend some time here: http://www.ruby-doc.org/core-1.9.3/

--
Hassan Schroeder ------------------------ hassan.s...@gmail.com
http://about.me/hassanschroeder
twitter: @hassan

Jordon Bedwell

unread,
Jan 5, 2013, 8:02:44 PM1/5/13
to rubyonra...@googlegroups.com
On Sat, Jan 5, 2013 at 1:49 PM, Jean <joso...@gmail.com> wrote:
> I have the following array on my rails console:
>
> u.favorites
>
> [#<Favorite id: 20, candidate_id: 6, ...>, #<Favorite id: 21, candidate_id:
> 7,..">, #<Favorite id: 22, candidate_id: 8, ...">, #<Favorite id: 23,
> candidate_id: 9, ...">, #<Favorite id: 24, candidate_id: 10, ...">]
>
> As you can see, I have candidate_id:6, candidate_id:7, candidate_id:8,
> candidate_id:9, candidate_id:10. But if I try this:
>
> u.favorites.include?(:candidate_id => 5) o canidate 6, 7, 8, 9 or 10 I get
> false.

u.favorites.keep_if { |f| f.canidate_id == 5 }
Reply all
Reply to author
Forward
0 new messages