Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find values in common between two arrays

Tags:

ruby

If I want to compare two arrays and create an interpolated output string if an array variable from array y exists in x how can I get an output for each matching element?

This is what I was trying but not quite getting the result.

x = [1, 2, 4] y = [5, 2, 4] x.each do |num|   puts " The number #{num} is in the array" if x.include?(y.each) end #=> [1, 2, 4] 
like image 372
sayth Avatar asked Apr 19 '12 14:04

sayth


1 Answers

You can use the set intersection method & for that:

x = [1, 2, 4] y = [5, 2, 4] x & y # => [2, 4] 
like image 120
Abe Voelker Avatar answered Sep 28 '22 08:09

Abe Voelker