我的代码是:
hash = { two: 2, three: 3 }
def hash_add(hash, new_key, new_value)
temp_hash = {}
temp_hash[new_key.to_sym] = new_value
temp_hash.merge!(hash)
hash = temp_hash
puts hash
end
hash_add(hash, 'one', 1)
Run Code Online (Sandbox Code Playgroud)
在方法中,puts hash返回{ :one => 1, :two => 2, :three => 3 },但是当hash1放入方法时,它在之后保持不变.这就像赋值不在函数之外.
我想我可以返回更新的哈希并在方法之外设置我想要更改的哈希:
hash = hash_add(hash, 'one', 1)
Run Code Online (Sandbox Code Playgroud)
但我只是不明白为什么我给哈希的赋值不会超出方法.
我有这个,有效:
def hash_add(hash, new_key, new_value)
temp_hash = {}
temp_hash[new_key.to_sym] = new_value
temp_hash.merge!(hash)
hash.clear
temp_hash.each do |key, value|
hash[key] = value
end
end
Run Code Online (Sandbox Code Playgroud)
这给了我调用这个方法时我想要的东西,但是像这样重建哈希似乎有点过分了.
Bal*_*ala 13
这个怎么样?
hash1 = { two: 2, three: 3 }
#add a new key,value
hash1 = Hash[:one,1].merge!(hash1) #=> {:one=>1, :two=>2, :three=>3}
Run Code Online (Sandbox Code Playgroud)
示例#2:
h = { two: 2, three: 3 }
def hash_add(h,k,v)
Hash[k.to_sym,v].merge!(h)
end
h = hash_add(h, 'one', 1) #=> {:one=>1, :two=>2, :three=>3}
Run Code Online (Sandbox Code Playgroud)
Ruby通过值将对象传递给方法,但是值是对象的引用,因此当您hash=temp_hash在add_hash方法中设置时,该更改仅适用于方法内部.方法外的哈希值不变.
def hash_add(hash, new_key, new_value)
temp_hash = {}
temp_hash[new_key.to_sym] = new_value
temp_hash.merge!(hash)
hash = temp_hash
hash
end
h2 = hash_add(hash, 'one', 1)
hash
=> {:two=>2, :three=>3}
h2
=>{:one=>1, :two=>2, :three=>3}
Run Code Online (Sandbox Code Playgroud)
如果要更新哈希值,则需要替换哈希的内容而不是像清除并重新添加值那样在新对象上重新点哈希.您也可以使用该replace方法.
def hash_add(hash, new_key, new_value)
temp_hash = {}
temp_hash[new_key.to_sym] = new_value
temp_hash.merge!(hash)
hash.replace temp_hash
end
Run Code Online (Sandbox Code Playgroud)
在" 是通过引用还是通过值传递Ruby? "中有一些关于传值的好图表.