How do you find an item that satisfies multiple conditions?

B

Bob Sanders

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?
 
C

Chad Fowler

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
}

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
 
S

Stefano Crocco

Alle Monday 01 December 2008, Bob Sanders ha scritto:
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?

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

Stefano
 
B

Bob Sanders

Chad and Stefano! Thank you!! =)

That was so quick. Thanks guys!

(Chad, pleasantly surprised you answered..I LOVE your work!)
 
R

Robert Dober

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

--=20
Ne baisse jamais la t=EAte, tu ne verrais plus les =E9toiles.

Robert Dober ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top