让我先说明我刚开始学习红宝石......
我有任何由哈希组成的数组,并且数组彼此嵌套。它看起来像这样:
people =
[
{
"John Doe" => {
"phone" => "555-555-555",
"company" => "Company name",
"children" => [
"John",
"Jane",
"Annamarie"
]
},
"Jane Smith" => {
"phone" => "555-555-5555",
"company" => "company name",
"children" => [
"Steven"
]
}
}
]
我如何添加一个新的哈希值,其中人名作为键,新哈希值是值?例如。我想添加“配偶”,所以哈希看起来像这样:
people =
[
{
"John Doe" => {
"phone" => "555-555-555",
"company" => "Company name",
"children" => [
"John",
"Jane",
"Annamarie"
],
"spouse" => "Jane Doe"
},
"Jane Smith" => {
"phone" => "555-555-5555",
"company" => "company name",
"children" => [
"Steven"
],
"spouse" => "John Smith"
}
}
]
答案 0 :(得分:3)
您可以使用select
获取哈希,并将“John Doe”作为键...
search_user = "John Doe"
person = people.select{|p| p.has_key?(search_user)}.first
person[search_user]['spouse'] = "Jane Doe" if person
最后一行if person
的原因是处理没有找到“John Doe”的情况。