Is there an opposite of include? for Ruby Arrays?

前端 未结 11 1760
孤街浪徒
孤街浪徒 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:16

    How about the following:

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

    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

    0 讨论(0)
  • 2020-12-23 13:22
    module Enumerable
      def does_not_include?(item)
        !include?(item)
      end
    end
    

    Ok, but seriously, the unless works fine.

    0 讨论(0)
  • 2020-12-23 13:22

    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
    
    0 讨论(0)
  • 2020-12-23 13:23

    Can you use:

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

    unless is opposite of if, or you may use reject.

    You can reject the not-required elements:

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

    after the getting the results you can do your implementation.

    0 讨论(0)
  • 2020-12-23 13:32

    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.

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