Chuck Smithson Chuck Smithson - 1 year ago 49
Ruby Question

Need to create a Hash using user input in Ruby

The goal is to get the user to enter 3 separate numbers and have the script store those in a Hash, output the values, and then add all the numbers in the hash. The script I'm working on keeps erroring out, and I was hoping for some guidance on how to correct it.

puts "Enter first number"
puts "Enter second number"
puts "Enter third number"
puts "The numbers entered were"
userhash.each_value {|value| puts value}
puts "the sum is #{userhash.inject(:+)}"

I just finished doing this as an array with no issues and thought that doing it as a hash would be quite similar. Obviously it's not working as intended. Help is appreciated.

Error: rb:15:in '<main>': undefined method 'each_value' for [{:num3=>"3"}]:Array (NoMethodError)

I entered values 1, 2, 3 when prompted to test.

Answer Source

There's a lot of mistakes in this code. Here's a refactored version:

# Declare an empty hash with the { } notation
entries = { }

# Request input N times
(1..3).each do |n|
  puts "Enter number %d" % n

  # Add this entry to the hash, convert it to an integer with to_i
  entries[:"num#{n}"] = gets.chomp.to_i

# Add the numbers together and have a default of 0 in case the array
# is empty.
puts "the sum is %d" % entries.values.inject(0, :+)

Your original code was re-defining the userhash variable as an array with a hash in it. This new code organizes things into a single hash with multiple entries, though given how it's used, this isn't necessary. Instead you could do this:

sum = 0

(1..3).each do |n|
  puts "Enter number %d" % n
  sum += gets.chomp.to_i

puts "the sum is %d" % sum
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download