exclude? is defined as ! include?, meaning it is the exact opposite of include? . See the source. This means that it works for Arrays and Hashes too, as well as for Strings.
The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.
Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator.
Ruby printing array contentsThe array as a parameter to the puts or print method is the simplest way to print the contents of the array. Each element is printed on a separate line. Using the inspect method, the output is more readable. The line prints the string representation of the array to the terminal.
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)
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.
How about the following:
unless @players.include?(p.name)
....
end
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With