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

Shreemangal Sethi
Shreemangal Sethi
11,968 Points

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
Jeff Muday
Treehouse Moderator 24,879 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).


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

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