Connecting Tech Pros Worldwide Help | Site Map

Comparing Arrays

Newbie
 
Join Date: Feb 2008
Posts: 2
#1: Feb 8 '08
I'm a Ruby n00b trying to write a simple app, and I've been trying to find a way to do this for a while, but can't seem to find anything. Here is essentially what I want to do:


if array contains 1,2,3 or 4,5,6 then
execute this code

But the array may have many more numbers in it than that, and they won't be in the same order. All I've been able to find are things where the two arrays have to be exactly alike.
Expert
 
Join Date: May 2007
Posts: 213
#2: Feb 8 '08

re: Comparing Arrays


You can use 'include?' as necessary to determine if the array meets the requirements.
Expand|Select|Wrap|Line Numbers
  1. if array.include?(1)
  2. #do this
Newbie
 
Join Date: Feb 2008
Posts: 2
#3: Feb 8 '08

re: Comparing Arrays


But is there any way to check for multiple values? I realize that I could nest it, but that would be extremely inconvenient.
Expert
 
Join Date: May 2007
Posts: 213
#4: Feb 8 '08

re: Comparing Arrays


I'm not sure how your array is set up, so I can't really give you a specific answer, but you should be able to use set intersection or array difference.
Expand|Select|Wrap|Line Numbers
  1. #Set Intersection
  2. if array && [1,2,3] == [1,2,3]
  3.   #array contains 1,2,3, so do this
  4. end
  5.  
Reply


Similar Ruby / Ruby on Rails bytes