4

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
0

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry for the duplicated answer. Mine was even a little bit wrong.
Thank you v much :) the first option works but not the 2nd for some reason

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.