Learn Ruby the Hard Way – Exercise 25 Even More Practice

Here is my work for Exercise 25.

Exercise 25 code with comments
Exercise 25 code with comments
Ex25 module in irb
Ex25 module in irb

Study Drills
1. Take the remaining lines of the What You Should See output and figure out what they are doing. Make sure you understand how you are running your functions in the ex25 module.
I explain what we are typing into the irb window below:

Use of the Ex25 module explained.
Use of the Ex25 module explained.

2. The Ex25 module doesn’t have to be in a file named ex25.rb. Try putting it in a new file with a random name, then import that file and see how you still have Ex25 available even though the file you made does not have ex25 in it.
I saved a copy of the ex25.rb file as differentname.rb!

We can use our Ex25 module just the same as before.
We can use our Ex25 module just the same as before.

3. Try breaking your file and see what it looks like in irb when you use it. You will have to quit irb with quit()to be able to reload it.
I had a few accidental errors in this exercise to begin with. All of them were typos.

Here is an example error: In the error below, my text editor had automatically finished ‘shift’ into ‘shifting’ for me. This gives a NoMethodError, as there is no ‘shifting’ method for arrays. This was fixed by correcting the word to ‘shift’.

Error! No such method.
Error! No such method.

Summary
This exercise was quite exciting because I learned how to use ‘require‘ ! By using require, we can gain access to a method written in another Ruby file. For example, if I have first.rb and second.rb, I can gain access to the methods in first.rb by requiring it in second.rb’s code. However, directly calling the method in the second file is messy and pollutes the global namespace. To prevent this, we wrapped all the methods within a module (in this exercise, the module is called Ex25). Now we can access the functions by calling it through the module name: Ex25.break_words(sentence) for example.

The name of the Ruby file does not have to correlate with the module name. We can have our file named myrubyfile.rb and the module called Ex25. As long as we require ‘myrubyfile.rb’, we can use the Ex25 module and its functions.

 

Advertisements

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