Some thoughts on Object#try

Apologies in advance if this has been covered here before, but it's
hard to do a search on a term like "try"

First off, I've been thinking that the current behavior of try may not
be the most logical:

Compare

nil.to_s

=> ""

vs.

nil.try(:to_s)

=> nil

Would it not make more sense for NilClass to return nil on try only
for those methods it doesn't respond to itself? For the vast majority
of cases it won't make a difference, but it just seems more logical to
me that way.

Secondly, I'd like to suggest an alternate syntax for try, using a
proxy object:

i.e.

object.try.method_name

rather than

object.try(:method_name)

I've been using this myself for a while, and I find it more natural
than the send style syntax, which I also support for those cases where
it's needed.

Incidently, I also set up a not proxy, so that I can do

something.not.nil?

rather than

!something.nil?

Which I find reads better as well.

In any case, I can submit a patch with an of these changes, if there's
any interest?

Cheers,

mateo

You may want to take a look at some of the past discussion:

http://github.com/rails/rails/commit/51730792ca930a896361eb92354a42bc56903de1
https://rails.lighthouseapp.com/projects/8994/tickets/1425

before reopening this particular can of worms.

Mike

Thanks, I was aware of the discussion around the final implementation,
but had missed what came earlier. I didn't see anything regarding the
points I brought up, although I may have missed that as well.

In any case, I'm don't care much about NilClass#try returning nil as
it's never caused a problem for me, but I am quite partial to the
proxy syntax; is there a drawback to supporting that that I've missed?

mateo

>> object.try.method_name

Check out andand.

that's the same as this.

something.andand.somemethod