我有一组嵌套的哈希。我想将字符串“Assembly”添加到与[:dennis_ritche]相关联的数组值[:languages]
def adding_to_dennis
programmer_hash =
{
:grace_hopper => {
:known_for => "COBOL",
:languages => ["COBOL", "FORTRAN"]
},
:alan_kay => {
:known_for => "Object Orientation",
:languages => ["Smalltalk", "LISP"]
},
:dennis_ritchie => {
:known_for => "Unix",
:languages => ["C"]
}
}
programmer_hash[:dennis_ritchie][:languages] << "Assembly"
end
这是错误,我没有将Symbol隐式转换为整数“
答案 0 :(得分:1)
我认为您遇到的问题是您正在操纵方法内部的哈希值,结果无意中返回了错误的内容。此方法返回一个数组,因为它执行的最后一个操作(在{Array上<<
返回修改后的数组)。
要修复它,请定义执行操作的方法:
def add_to_hash(hash, programmer = :dennis_ritchie, language = 'Assembly')
hash[programmer][:languages] << language
end
使其独立于定义:
programmer_hash =
{
:grace_hopper => {
:known_for => "COBOL",
:languages => ["COBOL", "FORTRAN"]
},
:alan_kay => {
:known_for => "Object Orientation",
:languages => ["Smalltalk", "LISP"]
},
:margaret_hamilton => {
:known_for => "Apollo Program",
:languages => ["Assembly"]
},
:dennis_ritchie => {
:known_for => "Unix",
:languages => ["C"]
}
}
然后调用它来操纵哈希:
add_to_hash(programmer_hash)
然后更新programmer_hash
结构。