Ruby 将对象列表转换为哈希

Ruby 将对象列表转换为哈希,ruby,Ruby,在Ruby中,我有一个名为Things的对象列表,其中包含Id属性和value属性 我想创建一个散列,其中包含Id作为键和Value作为键的值 我试过: result = Hash[things.map { |t| t.id, t.value }] 其中things是things 但这并不奏效 class Thing attr_reader :id, :value def initialize(id, value) @id = id @value = value e

在Ruby中,我有一个名为
Things
的对象列表,其中包含
Id
属性和
value
属性

我想创建一个散列,其中包含
Id
作为键和
Value
作为键的值

我试过:

result = Hash[things.map { |t| t.id, t.value }]
其中
things
things

但这并不奏效

class Thing
  attr_reader :id, :value
  def initialize(id, value)
    @id = id
    @value = value
  end
end

cat = Thing.new("cat", 9)
  #=> #<Thing:0x007fb86411ad90 @id="cat", @value=9> 
dog = Thing.new("dog",1)
  #=> #<Thing:0x007fb8650e49b0 @id="dog", @value=1> 

instances =[cat, dog]
  #=> [#<Thing:0x007fb86411ad90 @id="cat", @value=9>,
  #    #<Thing:0x007fb8650e49b0 @id="dog", @value=1>] 

instances.map { |i| [i.id, i.value] }.to_h
  #=> {"cat"=>9, "dog"=>1}
外对花括号的内容是块,内对形成散列。 但是,如果一个散列是所需的结果(如Cary Swoveland所建议的),那么这可能会起作用:

result = things.each_with_object({}){| t, h | h[t.id] = t.value}
外对花括号的内容是块,内对形成散列。 但是,如果一个散列是所需的结果(如Cary Swoveland所建议的),那么这可能会起作用:

result = things.each_with_object({}){| t, h | h[t.id] = t.value}
@potashin,我相信“列表”意味着数组。你说“不起作用”是什么意思?它是否返回了错误的结果?它引发了一个例外吗?如果是后者,有什么例外?我看你的代码没有问题。@potashin,我相信“列表”意味着数组。你说“不起作用”是什么意思?它是否返回了错误的结果?它引发了一个例外吗?如果是后者,有什么例外?我看你的代码没有问题。
result = things.each_with_object({}){| t, h | h[t.id] = t.value}