method

include?

v1_8_7_330 - Show latest stable - Class: Array
include?(p1)
public

Returns true if the given object is present in self (that is, if any object == anObject), false otherwise.

a = [ "a", "b", "c" ]
a.include?("b")   #=> true
a.include?("z")   #=> false

5Notes

Test if one array includes the elements of another

mindloaf · May 1, 20094 thanks

You can just use a set difference (aka minus) to see if one array includes all elements of another

not_included = [1,2,3] - (1..9).to_a
not_included      # => []


not_included = [1,2,3,'A'] - (1..9).to_a
not_included      # => ["A"]

Use intersection to test if any of the one are in the other:

shared = [1,2,3,'A'] & (1..9).to_a
shared     # => [1, 2, 3]

Test if an array is included in another

anoiaque · Jun 22, 20123 thanks
== Array

class Array def included_in? array array.to_set.superset?(self.to_set) end end

[1,2,4].included_in?([1,10,2,34,4]) #=> true

Test if one array includes the elements of another v2

mutru · Feb 24, 20092 thanks

Maybe a bit more readable way to write the previous snippet would've been

puts "yay" if [1, 2, 3].all? { |i| (1..9).include?(i) }
# => "yay"

puts "nope" if [1, 2, 3, 'A'].any? { |i| not (1..9).include?(i) }
# => "nope"

Test if one array includes the elements of another

Overbryd · Feb 24, 2009

Recently I've written this little snippet:

puts "yay" if [1, 2, 3].each {|i| break unless (1..9).to_a.include?(i)}
# => "yay"

puts "nope" unless [1, 2, 3, 'A'].each {|i| break unless (1..9).to_a.include?(i)}
# => "nope"

Test if an array is included in another

colmac · Nov 15, 2013

a note for anoiaque solution...

before running you need to require set

require 'set'
class Array
def included_in? array
  array.to_set.superset(self.to_set)
end
end

[1,2,4].included_in?([1,10,2,34,4]) #=> true