Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

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

list = create_list()
puts list.inspect

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

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:


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!

Hey, no problem! :+1: