ruby - Ruby;如何更新这个中的嵌套哈希?

抱歉,有点太长了。我需要将 :hero 和 :heroine 的状态更改为“死亡”

def update_status
   epic_tragedy = {
      :montague => {
         :patriarch => {name: "Lord Montague", age: "53"},
         :matriarch => {name: "Lady Montague", age: "54"},
         :hero => {name: "Romeo", age: "15", status: "alive"},
         :hero_friends => [
            {name: "Benvolio", age: "17", attitude: "worried"},
            {name: "Mercutio", age: "18", attitude: "hot-headed"}
         ]
      },
      :capulet => {
         :patriarch => {name: "Lord Capulet", age: "50"},
         :matriarch => {name: "Lady Capulet", age: "51"},
         :heroine => {name: "Juliet", age: "15", status: "alive"},
         :heroine_friends => [
         {name: "Steven", age: "30", attitude: "confused"},
         {name: "Nurse", age: "44", attitude: "worried"}
         ]
      }
   }

我确实在方法中添加了下面的代码,但它显示错误。

epic_tragedy[:montague][:hero][:status] = “死”

epic_tragedy[:capulet][:hero][:status] = “死”

在我放这些线之前有什么额外的步骤吗?

回答1

epic_tragedy 是方法定义中的局部变量。不能从方法外部访问此类局部变量。

但是方法执行的时候会返回hash,所以试试

h = update_status
  #=> {:montague=>{
  #      :patriarch=>{:name=>"Lord Montague", :age=>"53"},
  #      :matriarch=>{:name=>"Lady Montague", :age=>"54"},
  #      :hero=>{:name=>"Romeo", :age=>"15", :status=>"alive"},
  #      :hero_friends=>[
  #        {:name=>"Benvolio", :age=>"17", :attitude=>"worried"},
  #        {:name=>"Mercutio", :age=>"18", :attitude=>"hot-headed"}
  #      ]
  #    },
  #    :capulet=>{
  #      :patriarch=>{:name=>"Lord Capulet", :age=>"50"},
  #      :matriarch=>{:name=>"Lady Capulet", :age=>"51"},
  #      :heroine=>{:name=>"Juliet", :age=>"15", :status=>"alive"},
  #      :heroine_friends=>[
  #        {:name=>"Steven", :age=>"30", :attitude=>"confused"},
  #        {:name=>"Nurse", :age=>"44", :attitude=>"worried"}
  #      ]
  #    }
  #   }
h[:montague][:hero][:status] = "dead"
h[:capulet][:heroine][:status] = "dead"
h #=> {:montague=>{
  #      :patriarch=>{:name=>"Lord Montague", :age=>"53"},
  #      :matriarch=>{:name=>"Lady Montague", :age=>"54"},
  #      :hero=>{:name=>"Romeo", :age=>"15", :status=>"dead"},
  #      :hero_friends=>[
  #        {:name=>"Benvolio", :age=>"17", :attitude=>"worried"},
  #        {:name=>"Mercutio", :age=>"18", :attitude=>"hot-headed"}
  #      ]
  #    },
  #    :capulet=>{
  #      :patriarch=>{:name=>"Lord Capulet", :age=>"50"},
  #      :matriarch=>{:name=>"Lady Capulet", :age=>"51"},
  #      :heroine=>{:name=>"Juliet", :age=>"15", :status=>"dead"},
  #      :heroine_friends=>[
  #        {:name=>"Steven", :age=>"30", :attitude=>"confused"},
  #        {:name=>"Nurse", :age=>"44", :attitude=>"worried"}
  #      ]
  #    }
  #   }

相似文章