Hi --

On Thu, 28 Nov 2002, Jeff de Vries wrote:

> Is there some reason the following methods on Array aren't included as
> standard?
>
> class Array
>   def and?
>     # return true if the provided block returns true for every element
>     each {|x| return false unless yield x} if block_given?
>     return true
>   end
>   def or?
>     # return true if the provided block returns true for at least one
> element
>     each {|x| return true if yield x} if block_given?
>     return false
>   end
> end
>
> I find these to be very useful, and was suprised to not see them.  Is
> there another way to get the same effect (including short circuit of
> evaluation as soon as a condition fails)?

Yes, you can use detect:

  a = [1,2,3,4]
  a.detect {|e| e == 2}

and just use the logic however you need it:

  puts "failure" unless a.detect {|e| e == 3}

etc.  (For simple cases like this you can also use include? )


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav