将哈希添加到哈希(Ruby)

时间:2016-03-25 00:41:06

标签: ruby hash

我尝试通过#Hash.new添加哈希没有成功,现在我正在尝试.merge根据论坛也取得了有限的成功。我正在尝试将#rand(1..100)添加到[0]而不用手动进入哈希。有什么想法吗?

#age = Hash.new
#email = Hash.new
#age2 = rand(1..100)
people = [
{
 "first_name" => "Bob",
 "last_name" => "Jones", 
"hobbies" => ["basketball", "chess", "phone tag"]
},
{
"first_name" => "Molly",
"last_name" => "Barker",
"hobbies" => ["programming", "reading", "jogging"]
},
{
 "first_name" => "Kelly",
"last_name" => "Miller",
"hobbies" => ["cricket", "baking", "stamp collecting"]
}
]

people[0].each do |w|
people.merge({:age => rand(1..100)})
puts "array 0 is #{w}"
end

puts p people

1 个答案:

答案 0 :(得分:2)

假设这是你的结构,你可以这样做:

people.each do |person|
  person['age'] = rand(1..100)
end

理想情况下,您希望使用符号样式的键。这意味着将它们声明为:

people = [
  {
     first_name: "Bob",
     last_name: "Jones",
     ...
  },
  ...
]

这样你可以像people[0][:first_name]那样访问它们。合并的哈希使用:age的符号键。请记住,在Ruby中,字符串和符号不相同,即'bob' != :bob。你应该使用像这样的常规结构的符号,更多任意数据的字符串。