gpt4 book ai didi

ruby-on-rails - Ruby - 是否可以将方法别名为安全导航运算符

转载 作者:数据小太阳 更新时间:2023-10-29 07:44:46 27 4
gpt4 key购买 nike

Ruby 2.3 引入了安全导航运算符,但我发现它的语法过于离散,在快速扫描代码时很容易错过。相反,我更喜欢 try 的语法,因为它看起来更加明显和有意。

所以我的问题是在 Ruby 2.3+ 中,有没有一种方法可以将安全导航运算符 &. 的方法别名或猴子修补为自定义方法名称,即。 s.fast_try(:upcase!).fast_try(:downcase) 而不是写 s&.upcase!&.downcase

主要思想是尝试提高另一种实现(例如 try 方法)的性能。不,我不关心 try 和 safe 导航操作符之间的细微行为差异。另外,如果无法避免,我不介意一些模糊的论证限制,只需指出即可。

最佳答案

我猜你可以选择像这样简单的东西

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 和 safe 导航运算符之间的细微行为差异。”,鉴于您已经编写了 gem 并注意到以下内容

Differences between FastTry and ActiveSupport#try

It is not our goal to maintain any consistency with the ActiveSupport version of the try method. I do however want to maintain a simple list of the differences. Please create a PR or Issue if you find a difference that should be documented here.

Nothing reported yet

我觉得值得一提的是,这里的 2 之间存在明显且可能令人心酸的差异,即 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

关于ruby-on-rails - Ruby - 是否可以将方法别名为安全导航运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50471518/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com