我正在努力按照标题所说的去做。这是我的代码:
school.each { |x| school[:students][x].merge!(semester:"Summer") }
我想我将问题定位到上面的“[x]”。如果我替换一个数组位置,例如“[2]”,它可以正常工作。如何使迭代工作?
如果以上信息还不够,或者您想提供更好的解决方案,请参阅下面的详细信息。谢谢!
我得到的错误信息:
file.rb:31:in []': no implicit conversion of Array into Integer (TypeError)
from file.rb:31:in
block in ' from file.rb:31:in each'
from file.rb:31:in
'
更改前的嵌套哈希如下:
school = {
:name => "Happy Funtime School",
:location => "NYC",
:instructors => [
{:name=>"Blake", :subject=>"being awesome" },
{:name=>"Ashley", :subject=>"being better than blake"},
{:name=>"Jeff", :subject=>"karaoke"}
],
:students => [
{:name => "Marissa", :grade => "B"},
{:name=>"Billy", :grade => "F"},
{:name => "Frank", :grade => "A"},
{:name => "Sophie", :grade => "C"}
]
}
我正在尝试将 :semester=>"Summer" 附加到最后四个哈希中的每一个。这是我想要的:
# ...preceding code is the same. Changed code below...
:students => [
{:name => "Marissa", :grade => "B", :semester => "Summer"},
{:name=>"Billy", :grade => "F", :semester => "Summer"},
{:name => "Frank", :grade => "A", :semester => "Summer"},
{:name => "Sophie", :grade => "C", :semester => "Summer"}
]
}