Question

I'm trying to loop through this hash, and if a value is nil make it a blank string.

What's wrong?

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

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

Was it helpful?

Solution

v is a local block variable - it evaluates to the value from the hash pair, but is otherwise separate from the "hash slot"; 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.


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]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top