From: Eugen Minciu Date: 2007-07-20T01:17:31+09:00 Subject: Re: RCR? Added syntax for chains that possibly return nil Excerpts from Stefan Rusterholz's message of Thu Jul 19 16:31:01 +0300 2007: > One type of construct in ruby that somewhat annoys me and IMHO reduces > readability is working around cases where an intermediate method might > return nil. Those cases are e.g. > > while (line = gets && line.chomp) > foo = (bar && bar.baz && bar.baz.quuz) || default # bar might be nil, so > might bar.baz and bar.baz.quuz > > There are some more constructs, most of you surely already used such > stuff or just spread it onto a bit more of lines. > While all of this is fine, maybe that could be improved. My RCR would be > to introduce a new syntax besides . for method invocation, which on the > first nil aborts any further method calls on it and returns nil. > > E.g. the above examples would become: > while line = gets->chomp > foo = bar->baz->quuz || default > > -> was the first best that came to my mind, if you have better ideas, > please state. > Unlike e.g. making nil to respond to every method returning self, this > solution would put the coder in power as to where he cares about getting > nil (e.g. he wants an exception if foo is nil, so he just writes > foo.bar, if he doesn't want one, he writes foo->bar) and where he just > wants to get the nil value back. > > Do you think this RCR is worth to make? > > Regards > Stefan > how about this ugly creature? class Object alias regular_method_missing method_missing def method_missing(meth) if meth.to_s[0]=='_'[0] return nil else regular_method_missing(meth) end end end puts "yay, it works" unless 3._foo._bar._baz Not exactly like your syntax but gets the job done. Also, you might want to consider the proper way(tm) of doing it (I think) begin foo.bar.baz.whatever rescue puts "yay it works" end Also works as a one liner: x = begin 3.foo.bar.baz; rescue; nil; end -- Eugen Minciu. Wasting valuable time since 1985.