jahrichie
jahrichie

Reputation: 1235

Find intersection of arrays

I'm having trouble making a simple form that finds the intersection of two arrays. The end goal is to find the intersection of two arrays of emails, but right now i'm simply testing with integers. Everything works in the controller, and if I hard code the arrays in the view I get the correct result. Below is my code

Rails console, everything is kosher:

1.9.3p374 :011 > _a
 => [1, 2, 3, 4] 
1.9.3p374 :012 > _b
 => [1, 2, 1, 1, 1] 
1.9.3p374 :013 > c = _a & _b
 => [1, 2] 

When I try pass the same values from a form, I get an empty array result (I'm passing both arrays into the view to ensure they're there.

Controller:

  def intersect 
    @array1       = [params[:a]]
    @array2       = [params[:b]]
    @intersection = @array1 & @array2
  end

Code in View:

Array 1: <%= @array1 %> <br>
Array 2: <%= @array2 %><br>
Intersection: <%=  @intersection %>

Result in browser:

Array 1: ["1,2,3,4,5"] 
Array 2: ["1,2,2,3,3"]
Intersection: []

Since I can get this to work hardcoded I'm sure i'm doing something newbish! Any help is beyond welcome!!!

Upvotes: 1

Views: 3227

Answers (1)

Andrew Marshall
Andrew Marshall

Reputation: 97014

Your arrays each contain a single element which is the string "1,2,3,4,5". You probably want an array with 5 elements instead ([1,2,3,4,5]). You can do so by splitting the array on a comma:

@array1 = params[:a].split(',')
@array2 = params[:b].split(',')

@intersection = @array1 & @array2
#=> ["1", "2", "3", "4", "5"]

Upvotes: 8

Related Questions