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

Shreemangal Sethi
Shreemangal Sethi
8,386 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
MOD
Jeff Muday
Treehouse Moderator 23,731 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!