我想你可以选择像这样简单的东西
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"]
虽然你的问题指出,“不,我不关心尝试和安全导航操作员之间的细微行为差异。”,鉴于您已经编写了 gem 并注意到以下内容
FastTry 和 ActiveSupport 之间的区别#try
我们的目标不是保持与 ActiveSupport 版本的 try 方法的一致性。然而,我确实想保留一个简单的差异列表。如果您发现应在此处记录的差异,请创建 PR 或问题。
还没有任何报道
我觉得应该谨慎地指出,两者之间存在明显的、可能令人心酸的差异:复制规格 https://repl.it/@engineersmnky/AStry-vs-and-Safe-Navigation为了显示差异,为了这个答案以及链接可能会消失的事实,本规范的输出如下:
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