Cen92
Cen92

Reputation: 171

Alter value of hash if key exists in hash

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

Answers (1)

rthbound
rthbound

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

Related Questions