我猜你可以用一些简单的东西
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 和安全导航运算符之间的细微行为差异。”,因为您已经编写了 gem 并注意到以下内容
FastTry 和 ActiveSupport#try 之间的区别
我们的目标不是保持与 try 方法的 ActiveSupport 版本的任何一致性。但是,我确实想保留一个简单的差异列表。如果您发现应在此处记录的差异,请创建 PR 或问题。
尚未报告任何内容
我认为谨慎地提及两者之间存在明显且可能令人心酸的差异,这里是 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