On Wed, 18 Jul 2007 10:52:06 +0900, Jeff Pritchard wrote:

> I'm a relative newbie.  I'm finally getting the hang of some of the
> syntactic sugar provided, such as the whole thing about using the "or"
> operator to provide a default value if something is nil:
> 
> foo = bar || "emptiness"
> 
> 
> One thing I keep running into over and over and over and over that I
> wish there was some syntactic sugar for is the whole business of calling
> a method on an object, and doing something intelligent if the object is
> nil.
> 
> If I have a string of stuff like:
> blah = foo.bar.split
> 
> what if bar is nil?  There are obvious long hand ways to deal with this,
> but then you loose the smoothness of lining up things like this in Ruby.
> 
> I guess what I want is some syntactic sugar that means "this object, or
> an empty one of these if this is nil", so that I would get an empty
> result instead of a nil object missing method error.
> 
> I would like to be able to write:
> blah = foo.bar||empty(bar).split
> 
> This could be written:
> blah = foo.bar||"".split
> 
> But that requires a well known object type for bar.  What if it is: blah
> = foo.bar.whatchamacallit()
> 
> where bar is some oddball object of your own imagining.
> 
> Have you veteran Rubyists come up with a nice way to write stuff like
> this that keeps the nice clean flow of Ruby's chaining in place, but
> solves the problems with potentially nil intermediate results?
> 
> thanks,
> jp

I happen to program in both Groovy and Ruby, and while I prefer Ruby's 
paradigms to Groovy's (they're actually geared to make quite different 
things convenient), I noticed Groovy's ?. operator and asked myself "Why 
doesn't Ruby have this?" The ?. operator in Groovy calls the method if 
the expression on the left side is non-null, and returns its value. It 
returns null of the object on the left side is null, and never calls the 
method. It might be a nice feature to adopt.

Probably the best way to do this in Ruby is
"blah = foo.bar rescue nil", although this has the potential to soak up a 
lot of other kinds of errors that you may actually want to propagate.

--Ken

-- 
Ken Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu/~kbloom1/