2013-11-23 37 views
0

我在一個破碎的地方。我能夠從@ set1中獲得數組,現在需要比較@ set1和@ set2,並查看有多少匹配。我可以讓@ array1正常工作,如果我在@ array2中有一個數組中的靜態數字,但不是當我使其變爲動態時。需要從陣列中找到匹配的控制器! Ruby on Rails

我需要一種方法來比較這兩個數組,並且現在處於虧損狀態!

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 
+0

在找到起點:http://stackoverflow.com/questions/5013880/ruby-compare- 2-arrays-for-matches-and-count-the-number-of-match-instances – nathanielelliott

+0

http://stackoverflow.com/questions/19107761/activerecord-find-and-only-return-selected-columns-aligned- with-id – nathanielelliott

回答

0

我覺得這裏的問題的一部分是,你可以結交新對象具有相同的屬性,但不正確的比較,該路口響應操作:&用途。

實施例:

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] 
# => [] 

您可以考慮映射每個陣列在一定的標識值(也許ID),並找到的那些陣列的交叉點。也就是說

@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 

或者,如果你想要的對象本身...

(@array1.map{|obj| obj.id} & @array2.map{|obj| obj.id}).map{ |id| Set.find(id) } 
+0

只是想說這個工作就像一個魅力。感謝您的幫助,它將我引導到我需要做的事情! – nathanielelliott