Learn Ruby the Hard Way – Exercise 18

Yay functions! This exercise didn’t have study drills, instead it has a checklist for writing and calling functions in Ruby.

Here is my work for Exercise 18.

Exercise 18 code
Exercise 18 code
Exercise 18 output
Exercise 18 output

What happens if you call a method that has not been defined? (For example, if we comment out lines 17-20.) You will get an error. The error is saying undefined method, which means Ruby cannot find a function called print_none, since we never defined it.

A simple analogy would be you are listing food items on a menu. (defining the functions) You have cheeseburgers, fries, and salads. Now someone comes along and says, hey I want sushi! This causes a problem since you do not have sushi. You would tell them, that is not an item on our menu. This is what Ruby is telling you, print_none is not a defined function.

No such function!
No such function!

This exercise was about learning how to write a function in Ruby, accepting no arguments, a fixed number of arguments, or multiple arguments. The * in *args is telling Ruby to take all the arguments in the function and put them into a list. We can unpack the arguments in this list similar to how we unpacked arguments in ARGV. Another way we can unpack the arguments, if we don’t know how many there are, is to go through the list by iterating through the list.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s