1

我正在使用如下所示的一组 OpenStruct 对象:

a=[<OpenStruct name="test1", x="6", id="1">,<OpenStruct name="test2", x="5", id="2"><OpenStruct name="test1", x="8", id="3">...]

我想对具有相同名称的 OpenStruct 对象进行分组,如下所示:

a=[<OpenStruct name="test1",x=["6","8"], id=["1","3"]>,<OpenStruct name="test2", x="5", id="2">]

我怎样才能做到这一点?

4

2 回答 2

1

您可以使用 group_by 和 map 方法。我认为代码是不言自明的。

a = [
  OpenStruct.new(name: "test1", x: "6", id: "1"),
  OpenStruct.new(name: "test2", x: "5", id: "2"),
  OpenStruct.new(name: "test1", x: "8", id: "3")
]

a.group_by(&:name).map do |name, as|
  OpenStruct.new(
    name: name,
    x: as.map(&:x),
    id: as.map(&:id)
  )
end
# => [#<OpenStruct name="test1", x=["6", "8"], id=["1", "3"]>, #<OpenStruct name="test2", x=["5"], id=["2"]>]
于 2013-09-23T14:10:34.917 回答
0

像这样的东西应该工作:

a = [
  OpenStruct.new(name: "test1", x: "6", id: "1"),
  OpenStruct.new(name: "test2", x: "5", id: "2"),
  OpenStruct.new(name: "test1", x: "8", id: "3")
]

a.each_with_object({}) { |o, h|
  h[o.name] ||= OpenStruct.new(name: o.name, x: [], id: [])
  h[o.name][:x] << o.x
  h[o.name][:id] << o.id
}.values
#=> [#<OpenStruct name="test1", x=["6", "8"], id=["1", "3"]>, #<OpenStruct name="test2", x=["5"], id=["2"]>]

请注意, for 的xid属性test2也会转换为数组。这通常是首选。

重命名属性以指示数组可能是个好主意,即ids代替id.

于 2013-09-23T13:26:12.793 回答