[英]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?)
是简写
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?) }
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.