[ruby-on-rails] include의 반대가 있습니까? 루비 배열의 경우?
내 코드에는 다음과 같은 논리가 있습니다.
if !@players.include?(p.name)
...
end
@players배열입니다. 피할 수있는 방법이 !있습니까?
이상적으로이 스 니펫은 다음과 같습니다.
if @players.does_not_include?(p.name)
...
end
답변
if @players.exclude?(p.name)
...
end
ActiveSupport은 추가 exclude?방법 Array, Hash등을 String. 이것은 순수한 루비가 아니지만 많은 루비리스트가 사용합니다.
답변
답변
다음은 어떻습니까 :
unless @players.include?(p.name)
....
end
답변
루비 만보고 :
TL; DR
사용 none?과 그것을 블록을 통과 ==비교를위한 :
[1, 2].include?(1)
#=> true
[1, 2].none? { |n| 1 == n }
#=> false
Array#include?하나의 인수를 허용 ==하고 배열의 각 요소를 확인하는 데 사용 합니다.
player = [1, 2, 3]
player.include?(1)
#=> true
Enumerable#none?하나의 인수를 허용 할 수도 있는데,이 경우 ===비교에 사용됩니다. 반대 행동을 얻기 위해 include?매개 변수를 생략 ==하고 비교에 사용하는 블록을 전달합니다 .
player.none? { |n| 7 == n }
#=> true
!player.include?(7) #notice the '!'
#=> true
위의 예에서 실제로 다음을 사용할 수 있습니다.
player.none?(7)
#=> true
때문 Integer#==와 Integer#===동일합니다. 그러나 다음을 고려하십시오.
player.include?(Integer)
#=> false
player.none?(Integer)
#=> false
none?false때문에를 반환합니다 Integer === 1 #=> true. 그러나 실제로 합법적 인 notinclude?방법은 반환해야합니다 true. 우리가 전에했던 것처럼 :
player.none? { |e| Integer == e }
#=> true
답변
module Enumerable
def does_not_include?(item)
!include?(item)
end
end
알았지 만 진지하게 그렇지 않으면 제대로 작동합니다.
답변
사용 unless:
unless @players.include?(p.name) do
...
end
답변
사용할 수 있습니까 :
unless @players.include?(p.name) do
...
end
unless이 (가) 반대 if이거나 사용할 수 있습니다 reject.
할 수 있습니다 reject하지 않은 필수 요소 :
@players.reject{|x| x==p.name}
결과를 얻은 후에 구현을 수행 할 수 있습니다.
