Is there an opposite of include? for Ruby Arrays?

前端 未结 11 1761
孤街浪徒
孤街浪徒 2020-12-23 13:11

I\'ve got the following logic in my code:

if !@players.include?(p.name)
  ...
end

@players is an array. Is there a method so

相关标签:
11条回答
  • 2020-12-23 13:33

    Looking at Ruby only:

    TL;DR

    Use none? passing it a block with == for the comparison:

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

    Array#include? accepts one argument and uses == to check against each element in the array:

    player = [1, 2, 3]
    player.include?(1)
     #=> true
    

    Enumerable#none? can also accept one argument in which case it uses === for the comparison. To get the opposing behaviour to include? we omit the parameter and pass it a block using == for the comparison.

    player.none? { |n| 7 == n }
     #=> true 
    !player.include?(7)    #notice the '!'
     #=> true
    

    In the above example we can actually use:

    player.none?(7)
     #=> true
    

    That's because Integer#== and Integer#=== are equivalent. But consider:

    player.include?(Integer)
     #=> false
    player.none?(Integer)
     #=> false
    

    none? returns false because Integer === 1 #=> true. But really a legit notinclude? method should return true. So as we did before:

    player.none? { |e| Integer == e  }
     #=> true
    
    0 讨论(0)
  • 2020-12-23 13:36

    Use unless:

    unless @players.include?(p.name) do
      ...
    end
    
    0 讨论(0)
  • 2020-12-23 13:37

    Try something like this:

    @players.include?(p.name) ? false : true
    
    0 讨论(0)
  • 2020-12-23 13:39

    Here you go:

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

    You might have a look at the Ruby Style Guide for more info on similar techniques.

    0 讨论(0)
  • 2020-12-23 13:43
    if @players.exclude?(p.name)
        ...
    end
    

    ActiveSupport adds the exclude? method to Array, Hash, and String. This is not pure Ruby, but is used by a LOT of rubyists.

    Source: Active Support Core Extensions (Rails Guides)

    0 讨论(0)
提交回复
热议问题