2014-09-29 45 views
0

我有對象的數組,例如:獲取匹配的兩個元素的對象數組的獨特元素只有

[#<Something id: 34175, name: "abc", value: 123.3, comment: "something here">, 
#<Something id: 34176, name: "xyz", value: 123.3, comment: "something here">, 
#<Something id: 34177, name: "xyz", value: 227.3, comment: "something here sdfg">, 
#<Something id: 34178, name: "xyz", value: 123.3, comment: "something here sdfg">] 

我想返回不具有相同的名稱和值的所有元素。所以在這種情況下,退貨將是:

[#<Something id: 34175, name: "abc", value: 123.3, comment: "something here">, 
#<Something id: 34176, name: "xyz", value: 123.3, comment: "something here">, 
#<Something id: 34177, name: "xyz", value: 227.3, comment: "something here sdfg">] 

我所關心的是名稱和價值。

我試着將一個塊傳遞給uniq方法,但我不知道如何通過兩個元素而不是一個元素進行匹配。

+3

這應該這樣做:'a.uniq {|實例| [instance.name,instance.value]}'。 – 2014-09-29 16:44:35

+2

@CarySwoveland作爲回答 – 2014-09-29 16:45:14

+0

@CarySwoveland做到了!謝謝你的幫助。作爲回答發佈,我會接受。 – lundie 2014-09-29 16:50:48

回答

4

您想使用Array#uniq的形式佔用一個塊。

代碼

arr.uniq { |instance| [instance.name, instance.value] } 

class Something 
    attr_accessor :id, :name, :value, :comment 
    def initialize(id, name, value, comment) 
    @id = id 
    @name = name 
    @value = value 
    @comment = comment 
    end 
end 

arr = [Something.new(34175, "abc", 123.3, "something here"), 
     Something.new(34176, "xyz", 123.3, "something here"), 
     Something.new(34177, "xyz", 227.3, "something here sdfg"), 
     Something.new(34178, "xyz", 123.3, "something here sdfg")] 
    #=> [#<Something:0x000001012cc2f0 @id=34175, @name="abc", @value=123.3, 
    #  @comment="something here">, 
    # #<Something:0x000001012cc278 @id=34176, @name="xyz", @value=123.3, 
    #  @comment="something here">, 
    # #<Something:0x000001012cc200 @id=34177, @name="xyz", @value=227.3, 
    #  @comment="something here sdfg">, 
    # #<Something:0x000001012cc0e8 @id=34178, @name="xyz", @value=123.3, 
    #  @comment="something here sdfg">] 

arr.uniq { |instance| [instance.name, instance.value] } 

    #=> [#<Something:0x000001012cc2f0 @id=34175, @name="abc", @value=123.3, 
    #  @comment="something here">, 
    # #<Something:0x000001012cc278 @id=34176, @name="xyz", @value=123.3, 
    #  @comment="something here">, 
    # #<Something:0x000001012cc200 @id=34177, @name="xyz", @value=227.3, 
    #  @comment="something here sdfg">] 
相關問題