我想你可以选择一些简单的
class Object
def fast_try(meth,*args,&block)
self&.public_send(meth,*args,&block)
end
end
例如:
["string","STRING","pOw"].map do |s|
s.fast_try(:upcase!)
.fast_try(:chars)
.fast_try(:find, ->{"No S"}) { |a| a == "S" }
.fast_try(:prepend, "!")
end
#=> ["!S",nil,"!No S"]
当你的问题表明,
“不,我不关心Try和安全导航操作员之间的细微行为差异。”
,鉴于你已经写了一个宝石并注意到了以下几点
FastTry和ActiveSupport的区别
我们的目标不是保持与Try方法的ActiveSupport版本的任何一致性。不过,我还是想保持一个简单的差异列表。如果您发现此处应记录的差异,请创建公关或问题。
尚未报告
我认为谨慎的提一下,这里的两个词之间存在着明显的、潜在的尖锐的区别
Repl Spec
为了显示差异,为了这个答案,以及链接可能会死掉的事实,这个规范的输出如下:
ActiveSupport#try vs. Safe Navigation (&.)
#try
handles would be NoMethodError with nil (using #respond_to?)
does not work on a BasicObject
behaves like a method call
with no method name given
when block_given?
yields self to a block with arity > 0
evaluates block with arity == 0 in the context of self
when no block_given?
raises an ArgumentError
with a method_name given
a non nil object
uses public_send for message transmission
nil
calls NilClass#try and returns nil
#try!
does not handle NoMethodError
does not work on a BasicObject
behaves like a method call
with no method name given
when block_given?
yields self to a block with arity > 0
evaluates block with arity == 0 in the context of self
when no block_given?
raises an ArgumentError
with a method_name given
a non nil object
uses public_send for message transmission
nil
calls NilClass#try and returns nil
&. (safe navigation)
does not handle NoMethodError
raises a SyntaxError with no method name given when block_given?
raises a SyntaxError with no method name given when no block_given?
works on a BasicObject
does not act like a method call
with a method_name given
a non nil object
&. is not called
nil
returns nil without a method call