From: Rodrigo Rosenfeld Rosas Date: 2011-01-20T23:17:47+09:00 Subject: [ruby-core:34661] Re: Ruby operator equivalent to Groovy's "?." Em 20-01-2011 05:35, Giuseppe Bilotta escreveu: > 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) Yes, I've thought on that '.?' syntax too, but I wasn't very comfortable with it too... Maybe '&.' could fit. For instance, obj&.method could be assimilated to obj && obj.method. I don't know if that conflicts with what is current allowed in Ruby though. I just opened the discussion to see if someone comes with better suggestions... Best regards, Rodrigo.