boberczus
boberczus

Reputation: 3

Updating specific value in Ruby

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

Upvotes: 0

Views: 145

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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})

Upvotes: 3

Related Questions