boberczus boberczus - 2 months ago 21
Ruby Question

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:
I have a 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 aswell). Here's what i unsuccesfully 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 also tried messing around with hash.update but with no luck

Anyone help please? I've been stuck on it for like 3 hours already :/

Cheers,
Boberczus

Answer

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