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

How does the 2nd # add_list_item() gets called without explicitly calling it?

Hi in the code body after "list.inspect" how does it call for the # add_list_item without us calling it and prints the question "What is the item called? " ?

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,720 Points

Good question!

The thing I love most about coding is that there are many different right ways to do something, not just one way. Jason is particularly good at demonstrating the flexibility of Ruby and how we can combine operations.

Jason is being a little tricky with his coding by combining the list "push" method and a call to add_list_item(). The line below is executed by first calling "add_list_item()" which queries the user for item and quantity and returns a "hash". The hash is then "pushed" onto the list (also a hash).

list['items'].push(add_list_item())

He could have broken it down this way too (see below). It uses two lines to accomplish the same task, but you might think this is a little more straightforward.

user_response = add_list_item() # this asks the user for item and quantity
list['items'].push(user_response)

Good luck with your Ruby studies-- it is great fun to program!