내 코드에는 다음과 같은 논리가 있습니다.
if !@players.include?(p.name)
...
end
@players배열입니다. 피할 수있는 방법이 !있습니까?
이상적으로이 스 니펫은 다음과 같습니다.
if @players.does_not_include?(p.name)
...
end
내 코드에는 다음과 같은 논리가 있습니다.
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. 이것은 순수한 루비가 아니지만 많은 루비리스트가 사용합니다.
require 'active_support/core_ext/enumerable'
if flag unless @players.include?(p.name)어색하고 if flag && !@players.include?(p.name)부정을 사용합니다.
if하자 만 true조건을 통과, unless통과 할 수 false및 nil. 이것은 때때로 버그를 찾기 어렵게 만듭니다. 그러므로 저는 선호합니다exclude?
다음은 어떻습니까 :
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
사용 unless:
unless @players.include?(p.name) do
...
end
unless단일 include?절이있는 명령문에는 사용하는 것이 좋지만, 예를 들어, 어떤 것이 포함되어 있는지 Array다른 것을 포함 하지 않는지 확인해야하는 경우 include?with를 사용 하는 exclude?것이 훨씬 더 친숙합니다.
if @players.include? && @spectators.exclude? do
....
end
그러나 dizzy42가 위에서 말했듯이 사용 exclude?하려면 ActiveSupport 가 필요합니다
do유효 루비는? 오류가 발생합니다syntax error, unexpected end-of-input(을 제거하면 작동합니다do)