2014-09-29 31 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">] 
相关问题