lun*_*die 0 ruby arrays ruby-on-rails
我有一个对象数组,例如:
[#<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">]
Run Code Online (Sandbox Code Playgroud)
我想返回所有不具有相同名称和值的元素.所以在这种情况下,返回将是:
[#<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">]
Run Code Online (Sandbox Code Playgroud)
我所关心的只是名称和价值.
我尝试将一个块传递给uniq方法,但我无法弄清楚如何匹配两个元素而不仅仅是一个元素.
你想使用带有块的Array#uniq的形式.
码
arr.uniq { |instance| [instance.name, instance.value] }
Run Code Online (Sandbox Code Playgroud)
例
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">]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
654 次 |
| 最近记录: |