Reputation: 171
I am trying to alter the value of a hash if the key exists in the hash. I have my algorithm working to alter it to the correct value the only issue is that it alters all values in the hash rather than just the one I want. How do I only alter certain values in a hash?
I have tried the hash.has_key?(key) method and it still alters all my values
if @hash.has_key?(k)
@hash.select {|k,v| v.price = (v.price/100)}
else
print "Key not found"
end
Upvotes: 4
Views: 848
Reputation: 1341
has_key?
is not your problem... Hash#select
iterates over all the values.
Here's 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
Upvotes: 7