0

I am in a broken spot. I was able to get the array from into @set1 and now need to compare @set1 with @set2 and see how many matches there are. I can get the @array1 to work correctly if I have static numbers in an array in @array2 but not when I make it dynamic.

I need a way to compare these two arrays and am at a loss now!

def show
  @set1 = Set1.find(params[:id])
  @set2 = Set2.where(:date => @set1.date)

  @array1 = [Set1.find(params[:id]).let1, Set1.find(params[:id]).let2]
  @array2 = [Winnings.where(:date => @set1.date).let1, Winnings.where(:date => @set1.date).let2]
  @intersection = @array1 & @array2
end

1 Answers1

0

I think part of the problem here is that you can make new objects with the same attributes but that do not respond properly to the comparisons that the intersection operator :& uses.

Example:

class Thing
  attr_reader :first,:last
  def initialize(first,last)
    @first = first
    @last = last
  end
end

thing1 = Thing.new("John","Smith")
thing2 = Thing.new("John","Smith")

thing1 == thing2
# => false

[thing1] & [thing2]
# => []

You might consider mapping each array to some identifying value (maybe id) and finding the intersection of those arrays. That is to say

@set1 = Set1.find(params[:id])
@set2 = Set2.where(:date => @set1.date)

@array1 = [Set1.find(params[:id]).let1, Set1.find(params[:id]).let2]
@array2 = [Winnings.where(:date => @set1.date).let1, Winnings.where(:date => @set1.date).let2]

@array1.map{|obj| obj.id} & @array2.map{|obj| obj.id}
# => an array of unique object ids that are in both @array1 and @array2

Or, if you want the objects themselves...

(@array1.map{|obj| obj.id} & @array2.map{|obj| obj.id}).map{ |id| Set.find(id) }
elreimundo
  • 6,186
  • 1
  • 13
  • 6