Parallel modification bypassing the ruby ​​hash

Suppose you have this:

def wipeProduct(hash, nameToDelete) hash.each do |i| key = i[0] productName = i[1].first hash.delete(key) if productName==nameToDelete end end 

I'm not sure if things can be removed from the hash while you repeat the pairs of hash key values. I checked the RI documentation, but I did not see anything about parallel modification in Hash.

I know you can rewrite this

 def wipeProduct(hash, nameToDelete) keysToDelete = [] hash.each do |i| key = i[0] productName = i[1].first keysToDelete << key if productName==nameToDelete end keysToDelete.each {|key| hash.delete(key) } end 

or even:

 def wipeProduct(hash, nameToDelete) hash.reject!{|key,value| nameToDelete==value.first} end 

but I want to know if the problem is simultaneous modification, as shown in the first example above? (It seems this is not when I run the code)

Question: Does anyone know what position while modifying with Hash? (... and other collections?) - and I, of course, would like links to resources documenting this if you want.

+4
source share
1 answer

As long as no other threads try to access the hash, any of these methods is accurate. If there are any other threads that could access this hash, then none of these approaches is explicitly thread safe. You will want to make them safe, just make sure your method gets locked during the modification of the hash, and everything will be fine.

Personally, I would go with a devastating reject_if! This is cleaner code and does the same without reproducing existing code.

+1
source

All Articles