Sburke0708 Sburke0708 - 5 months ago 24
Ruby Question

storing user input to an empty hash

I'm writing a basic program. I am starting out with an empty hash, and using gets.chomp and want to store the info into the hash so that it can be recalled later (in the same session).

runs = {}
puts "how many miles did you run?"
miles = gets.chomp
puts "how long did it take you?"
time = gets.chomp


... program continues

Later I would like to have the user enter 'review' to display this (and any others that were entered) as information:

runs.each do |miles, time|
puts "#{miles} miles in #{time} minutes."
end


I know I am missing something before/after the "gets.chomp". Any suggestions?

Answer

To add a key value pair to a hash, you would use runs[miles] = time.

So your code would look something like this:

runs = {}
puts "How many miles did you run?"
miles = gets.chomp
puts "How long did it take you?"
time = gets.chomp

runs[miles] = time

# When user enters `review`
runs.each do |miles, time|
    p "#{miles} miles in #{times} minutes."
end

That's not the only way to add a key/value pair to a hash, so you can look at all the methods available over in the rubydoc.