From: Robert Klemme Date: 2007-07-20T18:33:42+09:00 Subject: Re: syntactic sugar buzz 2007/7/19, Sam Smoot : > On Jul 17, 8:52 pm, 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 > > > > -- > > Posted viahttp://www.ruby-forum.com/. > > It feels like it could be shortened, perhaps the :type is unnecessary, > but I was thinking of something like this for my DataMapper to ease > the pain of using object graphs in simple tabular reporting views... > > class Object > def default(type) > self || type.new > end > end > > class Person > attr_accessor :name > def initialize(name) > @name = name > end > end > > people = [ Person.new('Bob'), nil ] > > for person in people > puts "Hello " + person.default(Person).name > end I think you can save more typing if you default the type parameter to self.class. Then you have puts "Hello " + person.default.name > Which isn't _too_ ugly I think. On the other hand you could end up > with something like this: > > puts @photo.default(Article).article.default(Category).category.name > > Instead of: > > puts @photo.article.category.name > > But that's obviously more than a bit contrived. Any ideas would be > welcome though... Hm... One thing I do not like about this is that there has to be a new object created for every "missing" instance. I'd do your sample differently: either remove nils from the array beforehand or add a " if person" at the end of the "puts" statement. Kind regards robert