簡単な質問がありました。次のコードを検討してください。
class Hash
def value_for(keys, value)
common = self
while keys.size > 1 and !common.nil?
common = common[keys.shift] || { }
end
common[keys.last] = value
end
end
このコードでは、ネストされたノードの配列と割り当てられる値を渡すことで、ネストされたハッシュを作成できることを願っています。
次のように動作するはずです。
hash = {
"message" => "hello world"
}
hash.value_for [ "nested", "message" ], "hello world"
hash
#=> {
"message" => "hello world",
"nested" => {
"message" => "hello world"
}
}
hash.value_for [ "second", "nested", "message" ], "hello world"
hash
#=> {
"message" => "hello world",
"nested" => {
"message" => "hello world"
},
"second" => {
"nested" => {
"message" => "hello world"
}
}
}
何らかの理由で、新しいハッシュを作成するときにコードが機能しません。何か関係があるのではないかと疑っているcommon = common[keys.shift] || { }
誰か助けてくれませんか?私は愚かな何かが欠けていると感じています....
どうもありがとう