From: Robert Dober Date: 2008-06-12T03:18:53+09:00 Subject: Re: each with else On Wed, Jun 11, 2008 at 7:19 PM, Martin DeMello wrote: > On Wed, Jun 11, 2008 at 9:54 AM, Thorsten Müller wrote: >> >> hmmmm, maybe the RCR should be even more comprehensive and >> request for a completely new language construct that would allow >> to built new core commands, based on multiple blocks. >> Not only if/then, but case/when also. >> >> But that's too much for now, a new each would be enough... > > More simply, you can define an Object#if_empty > > class Object > def if_empty > yield if self.empty? > end > end > > a.each {|x| do something}.if_empty { do something else } > > this relies on the fact that obj#each returns obj. > > martin > > Martin I think you did not read my reply reagrding this technique, it is funny though that you want to define Object#is_empty, I would say that the Ruby way would be Object#empty? I gave an implementation for Enumerable#empty? using #last, this was an error because there is no Enumerable#last, I tested with Range only. But the point is that I started to think about "emptiness" as a concept. The first idea was class Object def empty?; instance_variables.all?{ |ivar| instance_variable_get( ivar ).nil? } end end now one needs to redefine empty? for all classes including Enumerable of course, because to_a.empty is simply not an option of course. But I am sure that emptiness might be a concept that could be generalized from arrays and hashes. Cheers Robert -- http://ruby-smalltalk.blogspot.com/ --- As simple as possible, but not simpler. Albert Einstein