From: dblack@... Date: 2006-09-28T08:33:03+09:00 Subject: Re: Injecting truth Hi -- On Thu, 28 Sep 2006, Ken Kunz wrote: > I had a scenario arise today where I needed an iterator with similar > semantics as Enumerable#all?, but non-short-circuiting. We came up with > a fairly elegant solution (imho), so I thought I'd be a good rubyzen > and share :) > > 1) First... the standard #all? (short-circuits): > > irb> (1..5).all? { |i| puts i; i < 3 } > 1 > 2 > 3 > => false > > 2) Non-short-circuiting version (injecting truth): > > irb> (1..5).inject(true) { |retval, i| puts i; retval &&= (i < 3) } > 1 > 2 > 3 > 4 > 5 > => false > > 3) One more way (though I like #2 better) > > irb(main):016:0> (1..5).partition { |i| puts i; i < 3 }.last.empty? > 1 > 2 > 3 > 4 > 5 > => false Cool. I want to play too :-) >> [*1..5].map {|i| puts i; i < 3 }.all? 1 2 3 4 5 => false David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org