From: Giuseppe Bilotta Date: 2011-01-20T16:35:09+09:00 Subject: [ruby-core:34646] Re: Ruby operator equivalent to Groovy's "?." On Thu, Jan 20, 2011 at 1:27 AM, Rodrigo Rosenfeld Rosas wrote: > One of the few things I like in Groovy that Ruby doesn't support is the '?.' > operator. For instance: > > obj?.somePropertyName?.anotherGreatPropertyName?.anotherOne > > This is the same as: > > (obj == null ? null : (obj.somePropertyName == null ? null : > (obt.somePropertyName.anotherGreatPropertyName == null ? null : > obt.somePropertyName.anotherGreatPropertyName.anotherOne))) > > Unfortunately, this name cannot be used by Ruby since it accepts '?' as part > of a method name. I've seen some framework that declares a '_?' method for > doing this like 'obj._?.some_method._?.another_method'. > > I'm not sure what syntax would fit better for Ruby. I don't even know if > this is something the Ruby community is interested in as well, so I'd like > to hear your opinions on this feature. I think there's plenty of interest in such a feature, as it seriously cuts down on if or rescue clause. One interesting point about the Ruby syntax is that the ? is accepted in a method name, but not as a first character. So for future ruby versions we could extend the actual internal syntas with something like this: obj.?method.?method2.?etc i.e. swapping ? and . wrt to the Groovy syntax. However, I'm thinking that this syntax would better be reserved for checking for the method presence rather than for the nil'ness of the object (as in: call method if obj replies to method, otherwise return nil, etc) -- Giuseppe "Oblomov" Bilotta