获取仅匹配两个元素的对象数组的唯一元素

时间:2014-09-29 16:38:09

标签: ruby-on-rails ruby arrays

我有一个对象数组,例如:

[#<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方法,但我无法弄清楚如何通过两个元素进行匹配而不仅仅是一个。

1 个答案:

答案 0 :(得分:5)

您想要使用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">]