在Ruby中,如何将数组转换为哈希?我有一个像这样的数组
peaple [{"name":"Sam","year":"21"},
{"name":"cole","partition":"20"},
{"name":"bart","year":"21"}]
我想将此数组放入下面的哈希中,以便检查谁是21:
peaple {
person1 => {"name"=>"Sam","year"=>"21"},
person2 => {"name"=>"cole","partition"=>"20"},
person3 => {"name"=>"bart","year"=>"21"},
}
如何将此数组转换为哈希?我该如何检查谁是21岁?
您可以使用each_with_object
遍历“ peaple”,并使用前缀person加上当前元素(人)的索引作为键,将当前元素分配给新的哈希。
peaple
.each_with_object({})
.with_index(1) do |(person, hash), index|
hash["person#{index}"] = person
end
# {"person1"=>{:name=>"Sam", :year=>"21"},
# "person2"=>{:name=>"cole", :partition=>"20"},
# "person3"=>{:name=>"bart", :year=>"21"}}
类似这样的东西:
首先,它刚好被拼写为“人”;)