Alin Chiver Alin Chiver - 1 year ago 180
Ruby Question

Why I can't keep the hash updated in ruby?

I need to update this hash with as many items as the user wants. And I have a problem with updating it.
It only shows the last input from user.

For example in i = 2, the hash will only show the second key and value added, and I want both. Or if i = 3 i need all three inputs.

puts "how may items to add in hash?"

i=gets.chomp.to_i
for i in 1..i
puts "add key"
key = gets.chomp
puts "add value"
value = gets.chomp.to_f.round(2)

project = Hash.new()
project = {key => value}

project.each do |key, value|
puts "#{key} \t - \t #{value}%"
end
end


Anyone that can help?

Answer Source

Just move your variable initialization our of the loop. Right now you rewrite your project with blank hash on each iteration. That's why it stores only the last item. Here is your possible code:

puts "how may items to add in hash?"

project = {}
i=gets.chomp.to_i

for i in 1..i
  puts "add key"
  key = gets.chomp                   
  puts "add value"
  value = gets.chomp.to_f.round(2)

  project[key] = value
end

project.each do |key, value|
  puts "#{key} \t - \t #{value}%"
end

project.values.inject(&:+)

PS: Prefer {} over Hash.new() (https://github.com/bbatsov/ruby-style-guide#literal-array-hash)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download