From: Christoph Date: 2002-08-09T05:23:08+09:00 Subject: Re: Enumerable#any? (was: Re: Coding challenge (on Ruby Garden) [long]) wrote .... > > Yup, they are a generalization of && and || to Enumerables. > > > > module Enumerable > > def all? > > each {|e| return false unless yield e } > > return true > > end > > def any? > > each {|e| return true if yield e } > > return false > > end > > end > > At first glance I thought that #any? didn't add anything to just using > the Boolean value of the result of #detect... until I tried this: Hm, the #detect method was new to me;-) > > ar = [1,2,3,nil,5] > puts "nil found by any?" if ar.any? {|e| e == nil } > puts "nil found by detect" if ar.detect {|e| e == nil} In some sense module Enumerable def all? last = true each {|e| return e unless last = yield e } return last end def any? last = nil # or false? each { |e| return e if last = yield e } return last end end might have been a better (but sort of useless;-) generalization of Ruby's shortcut logic for && and ||. /Christoph