Ruby Ruby Collections Build a Grocery List Program Build a Grocery List Program: Part 2

Robert Smith
Robert Smith
2,144 Points

get.chomp.to_i always outputs the number 0, regardless of the string input. My code is below with the output following.

def create_list
  print "What is the list name? "
  name = gets.chomp

  hash = { "name" => name, "items" => Array.new }
  return hash
end

def add_list_item
  print "What is the item called? "
  item_name = gets.chomp

  print "How much? "
  quantity = gets.chomp.to_i

  hash = { "name" => item_name, "quantity" => quantity }
  return hash
end

list = create_list()
puts list.inspect
list['items'].push(add_list_item())

puts list.inspect

This is the output, and if you notice in the hash, quantity is zero:

treehouse:~/workspace$ ruby shopping_list.rb                                                    
What is the list name? Grocery                                                                  
{"name"=>"Grocery", "items"=>[]}                                                                
What is the item called? Milk                                                                   
How much? two                                                                                   
{"name"=>"Grocery", "items"=>[{"name"=>"Milk", "quantity"=>0}]}

[MOD: edited code block -srh]

1 Answer

Steve Hunter
MOD
Steve Hunter
Treehouse Moderator 57,627 Points

Hi Robert,

I don't think to_i converts "two" to 2. It converts "2" to 2. The thing entered as a string has to be capable of a direct conversion to an integer. If you entered "Three hundred and twenty six", it would not come up with 326. The gets method reads user input as a string; it is expecting a sentence. Sometimes, we ask for a number; it still expects a sentence, but if we enter "2", the to_i method can convert that to a 2 integer. If we enter a string like "two", that's a little beyond the capabilities of the to_i method - but there are methods that can do that - just not at this level.

I hope that helps! Enter 2, not two. :smile: :wink: :+1:

Steve.

Robert Smith
Robert Smith
2,144 Points

Awesome. I have been wracking my brain and I can't believe it was so simple. Thank you so much!