Include? on array of objects

Hi,
Is it possible to use include? on an array of objects? I would like to
find a particular property of my object.
Unless so, how would you do so?

Greg

Greg Ma wrote:

Hi,
Is it possible to use include? on an array of objects? I would like to
find a particular property of my object.
Unless so, how would you do so?

Greg

You can use Array#include?(arg) but it will return true only if arg is
an element of the array. For finding a particular property use #detect.

ar = [“a”, “b” , “cd”]
puts “found ‘a’” if ar.include?(‘a’)
puts “found single char!” if ar.detect{|el| el.size == 1}

hth,

Siep

ar = [“a”, “b” , “cd”]
puts “found ‘a’” if ar.include?(‘a’)
puts “found single char!” if ar.detect{|el| el.size == 1}

Ok thanks I have to use Detect

Hi –

On Fri, 7 May 2010, Greg Ma wrote:

ar = [“a”, “b” , “cd”]
puts “found ‘a’” if ar.include?(‘a’)
puts “found single char!” if ar.detect{|el| el.size == 1}

Ok thanks I have to use Detect

Other fun variations on the theme:

ar.find {|el| el.size == 1 } # synonym for detect
ar.any? {|el| el.size == 1 } # returns true/false, so kind of
# a hybrid of include? and find

David


David A. Black, Senior Developer, Cyrus Innovation Inc.

THE Ruby training with Black/Brown/McAnally
COMPLEAT Coming to Chicago area, June 18-19, 2010!
RUBYIST http://www.compleatrubyist.com