我需要从下面的数组中创建一个哈希,让它看起来像 - peoples_ages = {" Joe" => 25}。我可以使用each_with_index迭代它,但我不需要索引作为值,我需要这个人的年龄。相反,我想要使用Hash [people_array] ...或.each_with_object。是否最好使用.map而不是之后放入.to_h?
class Person
attr_reader :name, :age
def initialize(name, age)
@name = name
@age = age
end
end
nick = Person.new("Nick", 25)
jim = Person.new("Jim", 37)
bob = Person.new("Bob", 23)
rob = Person.new("Rob", 29)
sue = Person.new("Sue", 31)
peeps = [nick, jim, bob, rob, sue]
# iterate over peeps array to create a hash that looks like this:
# people_ages = {
# "Nick" => 25,
# "Jim" => 37,
# "Bob" => 23,
# etc...
# }
答案 0 :(得分:4)
peeps.each_with_object({}){|e, h| h[e.name] = e.age}
答案 1 :(得分:2)
Hash[peeps.map {|person| [person.name, person.age]} ]
或者如果Ruby 2.0
peeps.map {|person| [person.name, person.age]}.to_h