简体   繁体   中英

Is there a difference between foo.try(&:to_s?) and foo.try(:to_s?)

I thought try is always with symbol like foo.try(:to_s?) . But I found foo.try(&:to_s?) also works and I couldn't find difference between them.

Is there a difference between them?

foo.try(&:to_s?) is shorthand for

  1. Calling to_proc on :to_s? , this will give you something that's kinda like this: ->(thing) { thing.public_send(:to_s?) }
  2. Taking that Proc and make it into a block
  3. Passing it as a block parameter to try

So the whole thing becomes something similar to this:

foo.try { |f| f.public_send(:to_s) }

and when try receives a block parameter, it simply yields to that block if the receiver is something other than nil , so it becomes further equivalent to this:

foo.to_s

which in effect nullifies the guarding effect of try in this particular case.

On the other hand, foo.try(:to_s) , passes the symbol :to_s as an argument to the try .

So foo.try(:to_s?) isn't really equivalent to foo.try(&:to_s?) .

See for example:

"hey".try(:foo)
# => nil
"hey".try(&:foo)
# => NoMethodError: undefined method `foo' for "hey":String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM