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 4

Grocery List extra credit

Hi there, wrote down extra credit ,also added counting of products in the cart.But I want to count all quantity's.Like 6 eggs and 5 bread, will make 11 items in Basket/cart.Can't figure out how to do this,tried to do with each_value ,but it just give me 0..here is code,could someone suggested something to take a look,i dont need solution just basically methods or where to take a close look,i know i need to take a value from list['items'] and from there quantity..help

def create_list
  print"What is the list name?"
  name=gets.chomp
  hash={"name"=>name,"items"=>Array.new}
  return hash
end
def add_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
def print_separator(character="-")
 puts character*80
end
def print_list(list)
puts "List:#{list['name']}"
print_separator()
list["items"].each do |item|
  puts "\tItem: " +item['name'] +"\t\t" +
   "Quantity: "+ item['quantity'].to_s

  end
print_separator()
puts "Total products in cart: "+list['items'].count.to_s 
print_separator()
end

list=create_list()

puts"Great!Now add some items to your cart."
list['items'].push(add_item())
puts "Do you want to add more item?(Yes/No)"
more_item=gets.chomp
while more_item=="Yes" ||more_item=="yes" do
 list['items'].push(add_item())
  puts "Do you want to add more item?(Yes/No)"
  more_item=gets.chomp
  break if more_item=="No"|| more_item=="no"
  end
puts "Here is you shopping list"

print_list(list)

1 Answer

Michael Hulet
Michael Hulet
47,913 Points

In your code, list["items"] is an Array. What you're trying to do here is find the numbers of objects that are in an array. In ruby, you do this with the Array#length method

thanks,Michael. I found solution another way with ''' each do'''. but also i will try your method:)