Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Zans Litinskis
Zans Litinskis
2,049 Points

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
MOD
Michael Hulet
Treehouse Moderator 47,826 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

Zans Litinskis
Zans Litinskis
2,049 Points

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