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

Nicolas Hémidy
Nicolas Hémidy
8,481 Points

Ruby loops - conditionals

Hello everyone,

I have an issue with my code below. I want to establish two conditions :

  • the user can add an item if he types "yes"
  • the user can add 4 items maximum

I do not suceed to set up the second condition. Please find my code below.

def create_list()
  puts "What is the name of your list? :"
  name = gets.chomp

  hash = {"name"=>name, "items"=>[]}
  return hash
end

def add_list_items()
  puts "Which item? :"
  item_name = gets.chomp

  puts "How much? :"
  quantity = gets.chomp.to_i

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

def separator()
  puts "-"*80
end

def print_list(list)
  puts "Here is your #{list['name']} list"
  separator()

  list["items"].each do |item|
    puts "\tItem: " + item['name'] + "\t\t\t" +
         "Quantity: " + item['quantity'].to_s
  end
  separator()
end

list = create_list()

loop do
  i = 1
  puts "Do you want to add an item? (yes/no) :"
  answer_user = gets.chomp 
  if i < 4 && answer_user == "yes"
    list['items'].push(add_list_items())
    i += 1
  else
    break
  end
end

print_list(list)

I really thank you in advance, Nicolas

2 Answers

L B
L B
28,323 Points

Your iterator (i) was inside the loop and its value was reset every time the loop ran. So, i+= 1 had no affect. Also, you want to start your iterator at 0 if you are using the < operator. Correct answer is:

list = create_list()

i = 0
loop do
  puts "Do you want to add an item? (yes/no) :"
  answer_user = gets.chomp 
  if i < 4 && answer_user == "yes"
    list['items'].push(add_list_items())
    i += 1
  else
    puts "Sorry, you can't add anymore items"
    break
  end
end

print_list(list)