Modules are another way to reuse the code. You can create some methods or constant variables, and use them with different classes. You may think about modules as libraries - you wrote some code once, and then you can inject it in some other part of your code.
To create a module, use following syntax:
To inject a module somewhere, you would need to use:
module SomeModule # module code goes here, just like in classes end
As an example, we could make a method
jump_height for all of our classes, that
would calculate how high can each of class objects jump.
The code should be pretty easy to understand, we did not change a lot
here: We have added a new module with method
in it, which returns a height according to object's class and size.
Then we included this module in all our classes and asked Ruby
values for each object.
Result should look like this:
Seems like we covered all main topics about Ruby! Unfortunately even if book's main goal would be to teach Ruby, we couldn't cover everything in depth anyway, because the programming language is not just variables and classes. You may want to check some additional books about Ruby, and to practice it yourself just a little bit. When ready, please proceed to the second chapter, where we start to make our first iOS application with Rubymotion.