From: Intransition Date: 2009-11-14T01:30:54+09:00 Subject: Re: Enumerable#find_yield, useful shortcut? better name? On Nov 13, 9:12 am, Benoit Daloze wrote: > As Aaron, > I prefer the simple built-in method, with what u want to do with the object > after: > > obj1.foo? #=> false > obj2.foo? #=> true > obj2.foo  #=> "value" > > [obj1, obj2].find_yield { |obj| obj.foo if obj.foo? } #=> "value" > > [obj1, obj2].find { |obj| obj.foo? }.foo #=> "value" > > Even more concise ... > The only problem I see is if we don't find, we'll call foo on nothing(nil). > > So to have the same behavior: > x = [obj1, obj2].find(nil) { |obj| obj.foo? } > x.foo unless foo.nil? #=> "value" > > And I think it's quite normal we have to manage with a structure(the if) how > to manage when we didn't find. > > But I'm probably missing a special case. Could you give a example in > situation, to see if it is easier to read or not? I think you make a good point. The difference lies in where you are able to put the logic. Eg. x = [obj1, obj2].find{ |obj| obj.foo? } y = x ? do_something_with(x.foo) : nil vs. y = [obj1, obj2].find_yield do |obj| do_something_with(obj.foo) if obj.foo? end These are functionally equivalent, so really this is just a matter constructional preference. If there were a way to make the former more concise, then the case for the later would probably be moot, but I'm not sure there is.