Forum: Ruby How to use include? on an array of objects

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.
Fernando P. (Guest)
on 2008-11-21 19:48
I have the following array:

[ product1, product2, product3 ]

All products are of type Product. The Product class defines isntance
attributes such as: title, description, price.

Can I use include? to check if the array has a product which price is
zero? if not what would I need to do? Iterate over each product and set
a variable if a match is found?
Shane E. (Guest)
on 2008-11-21 20:02
(Received via mailing list)
Use the 'select' method of array
http://ruby-doc.org/core/classes/Array.html#M002214
James C. (Guest)
on 2008-11-21 20:02
(Received via mailing list)
>
> I have the following array:
>
> [ product1, product2, product3 ]
>
> All products are of type Product. The Product class defines isntance
> attributes such as: title, description, price.
>
> Can I use include? to check if the array has a product which price is
> zero? if not what would I need to do?


You probably want any? :

product_array.any? { |p| p.price.zero? }
Matthew M. (Guest)
on 2008-11-21 20:09
(Received via mailing list)
On Nov 21, 2008, at 11:44 AM, Fernando P. wrote:

> a variable if a match is found?
Given arr = [ product1, product2, product3 ], and you have a 'price'
method on your products:

If you want to find the first item of price zero:

    arr.find { |prod| prod.price.zero? }

If you want to find all items of price zero:

    arr.select { |prod| prod.price.zero? }

If you just want to know that at least one item has zero price:

    arr.any? { |prod| prod.price.zero? }
Ryan D. (Guest)
on 2008-11-21 21:57
(Received via mailing list)
On Nov 21, 2008, at 09:44 , Fernando P. wrote:

> a variable if a match is found?
c'mon guys... teach a man to fish.

Fernando, check out ri. ri is your friend(tm).

% ri Array
% ri Enumerable

(Array includes Enumerable). There is a LOT of good stuff in
Enumerable. You should poke around and learn as much of it as you can:

% ri Enumerable.find
% ri Enumerable.find_all

etc.

Other places to look are http://ruby-doc.org/ and the PragProg pickaxe
book (Programming Ruby, 2nd ed).
This topic is locked and can not be replied to.