Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining whether one array contains the contents of another array in ruby

Tags:

arrays

ruby

In ruby, how do I test that one array not only has the elements of another array, but contain them in that particular order?

correct_combination = [1, 2, 3, 4, 5]
[1, 5, 8, 2, 3, 4, 5].function_name(correct_combination) # => false
[8, 10, 1, 2, 3, 4, 5, 9].function_name(correct_combination) # => true

I tried using include, but that is used to test whether [1,2,3].include?(2) is true or not.

like image 369
Andrew Grimm Avatar asked May 18 '10 07:05

Andrew Grimm


People also ask

How do you check if a value is contained in an array in Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.

What does .last do in Ruby?

Ruby | Array class last() function last() is a Array class method which returns the last element of the array or the last 'n' elements from the array. The first form returns nil, If the array is empty .

How do you compare two values in an array in Ruby?

Ruby arrays may be compared using the ==, <=> and eql? methods. The == method returns true if two arrays contain the same number of elements and the same contents for each corresponding element.

What does .first mean in Ruby?

Ruby | Array class first() function first() is a Array class method which returns the first element of the array or the first 'n' elements from the array.


2 Answers

You can use each_cons method:

arr = [1, 2, 3, 4, 5]
[1, 5, 8, 2, 3, 4, 5].each_cons(arr.size).include? arr

In this case it will work for any elements.

like image 126
Yossi Avatar answered Oct 29 '22 02:10

Yossi


I think it can be done simply.

class Array
  def contain? other; (self & other) == other end
end

correct_combination = [1, 2, 3, 4, 5]
[1, 5, 8, 2, 3, 4, 5].contain?(correct_combination) # => false
[8, 10, 1, 2, 3, 4, 5, 9].contain?(correct_combination) # => true
like image 33
sawa Avatar answered Oct 29 '22 04:10

sawa