0

I'm just starting my adventure with Ruby, and I have a problem. I've completed Codecademy's Ruby course, so I'm not THAT green, but i still don't know too much. Anyway. How can you update a specific value with an equation? Like, here is what I'm trying to do with the following hash:

hash = { "s1" => 2, "s2" => 3 }

What I want to do next, is get input via gets.chomp to get the key, and then acquire the amount to add to value (via gets.chomp as well). Here's what I have unsuccessfully tried:

name = gets.chomp
value = gets.chomp.to_i
hash.each do |x, y|
  if x == name
    y == y + value
  else
    puts "nope"
  end
end

I have also tried messing around with Hash#update but with no luck. Can anyone help please? I've been stuck on it for like 3 hours already :/

Cheers, Boberczus

1 Answer 1

3

Inside a block, both x and y are local variables, updating them makes no effect. You might map instead:

hash.map do |x, y|
  [x, if x == name
        y + value
      else
        puts "nope"
        y
      end
  ]
end.to_h

But the easiest way would be:

if hash[name]
  hash[name] += value
else
  puts "nope"
end

Using update:

hash.update({name => value})
Sign up to request clarification or add additional context in comments.

1 Comment

Hah! Thank you! Now I can move on. I was totally overcomplicating things. Gotta read documentation more carefully. Cheers.

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.