Tyl*_*itt 175 ruby ruby-on-rails
我的代码中有以下逻辑:
if !@players.include?(p.name)
...
end
Run Code Online (Sandbox Code Playgroud)
@players
是一个数组.是否有方法可以避免!
?
理想情况下,此代码段将是:
if @players.does_not_include?(p.name)
...
end
Run Code Online (Sandbox Code Playgroud)
小智 342
if @players.exclude?(p.name)
...
end
Run Code Online (Sandbox Code Playgroud)
的ActiveSupport增加的exclude?
方法Array
,Hash
和String
.这不是纯Ruby,但是被很多rubyists使用.
来源:Active Support Core Extensions(Rails指南)
Boz*_*sov 88
干得好:
unless @players.include?(p.name)
...
end
Run Code Online (Sandbox Code Playgroud)
您可以查看Ruby样式指南,了解有关类似技术的更多信息.
ila*_*sno 12
以下内容如何:
unless @players.include?(p.name)
....
end
Run Code Online (Sandbox Code Playgroud)
Sag*_*dya 10
TL; DR
使用none?
传递一个块==
进行比较:
[1, 2].include?(1)
#=> true
[1, 2].none? { |n| 1 == n }
#=> false
Run Code Online (Sandbox Code Playgroud)
阵列#包括哪些内容?
Array#include?
接受一个参数并用于==
检查数组中的每个元素:
player = [1, 2, 3]
player.include?(1)
#=> true
Run Code Online (Sandbox Code Playgroud)
枚举#没有?
Enumerable#none?
也可以接受一个参数,在这种情况下,它===
用于比较.为了得到相反的行为,include?
我们省略了参数并将其传递给==
用于比较的块.
player.none? { |n| 7 == n }
#=> true
!player.include?(7) #notice the '!'
#=> true
Run Code Online (Sandbox Code Playgroud)
要考虑的要点
在上面的例子中我们可以实际使用:
player.none?(7)
#=> true
Run Code Online (Sandbox Code Playgroud)
那是因为Integer#==
并且Integer#===
是等价的.但考虑一下:
player.include?(Integer)
#=> false
player.none?(Integer)
#=> false
Run Code Online (Sandbox Code Playgroud)
none?
返回false
因为Integer === 1 #=> true
.但真正合法的notinclude?
方法应该回归true
.就像我们之前做过的那样:
player.none? { |e| Integer == e }
#=> true
Run Code Online (Sandbox Code Playgroud)
如果您对!
- 运算符的反对主要是它需要放在您的检查前面,这会破坏您的打字流程,那么有一个方法.!
。您只需将其放在检查之后即可反转布尔值:
if @players.include?(p.name).!
Run Code Online (Sandbox Code Playgroud)
module Enumerable
def does_not_include?(item)
!include?(item)
end
end
Run Code Online (Sandbox Code Playgroud)
好吧,但严重的是,除非工作正常.