Forum: Ruby How do you find an item that satisfies multiple conditions?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bob S. (Guest)
on 2008-12-01 14:39
I know that to find an item that satisfies one condition, it's this:

@items.find {|item| item.product == product }

I thought I could try this to check that an item satisfies multiple
conditions:

@items.find {|item|
item.product == product
item.red == red
item.blue == blue
}

Of course, I'm not getting desirable results from that. Do you know how
I would correctly find an item that satisfies multiple conditions?
Chad F. (Guest)
on 2008-12-01 14:46
(Received via mailing list)
On Mon, Dec 1, 2008 at 6:34 AM, Bob S.
<removed_email_address@domain.invalid> wrote:
> item.blue == blue
> }
>

Hi Bob.  The find method returns a new collection including all
elements for which the block returns boolean true.  In this case, your
product and red comparisons happen but are not returned from the block
and are ignored.  Whaty ou want is ONE boolean expression combining
all of these comparisons:

@items.find{|item|
  item.product == product && item.red == red && item.blue == blue
}

Chad
Stefano C. (Guest)
on 2008-12-01 14:47
(Received via mailing list)
Alle Monday 01 December 2008, Bob S. ha scritto:
> item.blue == blue
> }
>
> Of course, I'm not getting desirable results from that. Do you know how
> I would correctly find an item that satisfies multiple conditions?

@items.find{|item| item.product == product && item.red == red &&
item.blue == blue}

Stefano
Bob S. (Guest)
on 2008-12-01 14:54
Chad and Stefano! Thank you!! =)

That was so quick. Thanks guys!

(Chad, pleasantly surprised you answered..I LOVE your work!)
Robert D. (Guest)
on 2008-12-01 19:58
(Received via mailing list)
On Mon, Dec 1, 2008 at 1:40 PM, Chad F. <removed_email_address@domain.invalid> 
wrote:
<snip>
> Hi Bob.  The find method returns a new collection including all
> elements for which the block returns boolean true.
I am afraid that you confused Enumerable#find with Enumerable#select
616/137 > ruby -e 'p [*0..9].find{|x| (x%2).zero? }'
0
617/138 > ruby -e 'p [*0..9].select{|x| (x%2).zero? }'
[0, 2, 4, 6, 8]
robert@siena:~/log/ruby 18:56:47
618/139 > ruby -e 'p [*0..9].select{|x| (x%2).zero? && (x%3).zero?}'
[0, 6]
HTH
Robert

--
Ne baisse jamais la tête, tu ne verrais plus les étoiles.

Robert D. ;)
This topic is locked and can not be replied to.