简体   繁体   English

foo.try(&:to_s?)和foo.try(:to_s?)之间有区别吗?

[英]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?) . 我认为try总是使用像foo.try(:to_s?)这样的symbol But I found foo.try(&:to_s?) also works and I couldn't find difference between them. 但我发现foo.try(&:to_s?)也有效,我找不到它们之间的区别。

Is there a difference between them? 它们之间有区别吗?

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

  1. Calling to_proc on :to_s? 调用to_proc :to_s? , this will give you something that's kinda like this: ->(thing) { thing.public_send(:to_s?) } ,这会给你一些类似的东西: ->(thing) { thing.public_send(:to_s?) }
  2. Taking that Proc and make it into a block 把那个Proc变成一个块
  3. Passing it as a block parameter to try 将其作为块参数传递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: 并且当try接收到一个块参数时,如果接收器不是nil ,它只会产生该块,所以它变得更加相当于:

foo.to_s

which in effect nullifies the guarding effect of try in this particular case. 这实际上取消了在这种特殊情况下try的防护效果。

On the other hand, foo.try(:to_s) , passes the symbol :to_s as an argument to the try . 另一方面, foo.try(:to_s)将符号:to_s作为参数传递给try

So foo.try(:to_s?) isn't really equivalent to foo.try(&:to_s?) . 所以foo.try(:to_s?)并不等同于foo.try(&:to_s?)

See for example: 参见例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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