Programing

include의 반대가 있습니까?

lottogame 2020. 5. 25. 08:03
반응형

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

비슷한 기술에 대한 자세한 내용 Ruby 스타일 가이드 를 참조하십시오.


다음은 어떻습니까 :

unless @players.include?(p.name)
  ....
end

루비 만보고

TL; DR

사용 none?과 그것을 블록을 통과 ==비교를위한 :

[1, 2].include?(1)
  #=> true
[1, 2].none? { |n| 1 == n  }
  #=> false

배열 #include?

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 @players.include?(p.name) do
  ...
end

사용할 수 있습니까

unless @players.include?(p.name) do
...
end

그렇지 않으면 if와 반대입니다.

또는 거부사용 하여 필요하지 않은 요소를 거부 할 수 있습니다.

@players.reject{|x| x==p.name}

결과를 얻은 후 구현을 수행 할 수 있습니다


Using unless is fine for statements with single include? clauses but, for example, when you need to check the inclusion of something in one Array but not in another, the use of include? with exclude? is much friendlier.

if @players.include? && @spectators.exclude? do
  ....
end

But as dizzy42 says above, the use of exclude? requires ActiveSupport


Try something like this:

@players.include?(p.name) ? false : true

Try this, it's pure Ruby so there's no need to add any peripheral frameworks

if @players.include?(p.name) == false do 
  ...
end

I was struggling with a similar logic for a few days, and after checking several forums and Q&A boards to little avail it turns out the solution was actually pretty simple.


I was looking up on this for myself, found this, and then a solution. People are using confusing methods and some methods that don't work in certain situations or not at all.

I know it's too late now, considering this was posted 6 years ago, but hopefully future visitors find this (and hopefully, it can clean up their, and your, code.)

Simple solution:

if not @players.include?(p.name) do
  ....
end

참고URL : https://stackoverflow.com/questions/10355477/is-there-an-opposite-of-include-for-ruby-arrays

반응형