Change hash value if key exists in hash

I am trying to change the hash value if the key exists in the hash. I have an operating algorithm to change it to the correct value, the only problem is that it changes all the values โ€‹โ€‹in the hash, and not just the one I want. How to change only certain values โ€‹โ€‹in a hash?

Have I tried the hash.has_key method? (key) and it still changes all my values

if @hash.has_key?(k) @hash.select {|k,v| v.price = (v.price/100)} else print "Key not found" end 
+4
source share
1 answer

has_key? not your problem ... Hash#select iterates over all values.

There are two options:

 @hash.select{|k,v| v.price /= 100 if k == key} 

or

 if @hash.has_key?(key) @hash[key].price /= 100 else print "Key not found" end 
+7
source

Source: https://habr.com/ru/post/1441113/


All Articles