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.
2c2f3ce7125411ff78a1d3e902aa2a4d?d=identicon&s=25 Bob Sanders (adistarmid)
on 2008-12-01 13: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?
77f306388bb6ae00ac0b0401e27cdc99?d=identicon&s=25 Chad Fowler (Guest)
on 2008-12-01 13:46
(Received via mailing list)
On Mon, Dec 1, 2008 at 6:34 AM, Bob Sanders
<small.business.strategy@gmail.com> 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
C40020a47c6b625af6422b5b1302abaf?d=identicon&s=25 Stefano Crocco (crocco)
on 2008-12-01 13:47
(Received via mailing list)
Alle Monday 01 December 2008, Bob Sanders 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
2c2f3ce7125411ff78a1d3e902aa2a4d?d=identicon&s=25 Bob Sanders (adistarmid)
on 2008-12-01 13:54
Chad and Stefano! Thank you!! =)

That was so quick. Thanks guys!

(Chad, pleasantly surprised you answered..I LOVE your work!)
703fbc991fd63e0e1db54dca9ea31b53?d=identicon&s=25 Robert Dober (Guest)
on 2008-12-01 18:58
(Received via mailing list)
On Mon, Dec 1, 2008 at 1:40 PM, Chad Fowler <chad@chadfowler.com> 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 Dober ;)
This topic is locked and can not be replied to.