@data, @x, @y, and @z are all arrays of the same type. I use @data in my view to iterate through it and display all the values.
@data = if params[:a] == "1"
@x
elsif params[:b] == "1"
@y
elsif params[:c] == "1"
@z
What I’d like to do is also intersect the arrays if multiple parameters are applied. So, for example, if ?a=1&b=2 is appended to the URL, then I’d like @data to equal @x & @y
I’m not sure how to write this code – what’s the easiest way to figure out which params == 1 and then intersect the corresponding arrays and store that in @data?
Fortunately, Ruby makes this easy!
This constructs an array of either arrays (if the parameter is present; you could check
== '1'if you wanted to be more specific) or nils (if it is not present).compactthen strips the nils out of the array, and we can then intersect the remaining values by callinginject(:&).The
injectcall iterates over your array of values, takes the first value, and then applies the&method with the next value as a parameter. It then takes the result and applies&with the third parameter, and so on, resulting in a final value which is the intersection of all of the arrays in the passed array.