简体   繁体   English

遍历哈希,无法更新值

[英]Looping through Hash, Can't Update Values

I'm trying to loop through this hash, and if a value is nil make it a blank string. 我试图遍历此哈希,如果值为nil,则将其设为空白字符串。

What's wrong? 怎么了?

my_hash = { "one"=>"foo", "two"=>"bar", "three"=>nil}

my_hash.each {|k,v| if v==nil then v="" end}

v is a local block variable - it evaluates to the value from the hash pair, but is otherwise separate from the "hash slot"; v是一个局部块变量 - 计算得出哈希对中的值,但与“哈希槽” 分开 as such, re-assigning to the variable does not affect the hash. 这样, 重新分配给变量影响所述散列。

You need to use my_hash[k] = "" to cause a side-effect on the actual hash object. 您需要使用my_hash[k] = ""对实际的哈希对象产生副作用。


An alternative to mutating the hash while it is being iterated (which is okay as long as keys are not changed) is to use a "functional" approach to create a new hash. 除了在哈希值迭代时对其进行突变(只要不更改键即可)的另一种方法是使用“功能”方法来创建新哈希值。 This is for reference; 仅供参考; not necessarily an argument to switch approaches. 不一定是切换方法的论点。

# for each pair in the hash, yield a corresponding output pair
result = my_hash.map do |k,v|
    [k, if v.nil? then "" else v]
end

# create a new hash from the result, which is [[k,v],..]
my_hash = Hash[result]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM