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:

        module SomeModule
          # module code goes here, just like in classes
To inject a module somewhere, you would need to use:
        include SomeModule

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.

        module Jump
          def jump_height
            if self.is_a?(Person)
              # average person can jump on a ~50cm height
            elsif self.is_a?(Dog) && @size == "Small"
              # small dogs don't usually jump very high
            elsif self.is_a?(Dog) && @size == "Medium"
              # medium dogs don't can jump higher that a human sometimes
            elsif self.is_a?(Dog) && @size == "Big"
              # big dogs can jump twice as high as a small dogs
            elsif self.is_a?(Cat) && @size == "Small"
              # I believe small cats can jump higher that dogs. What do you think?
            elsif self.is_a?(Cat) && @size == "Medium"
              # Same for medium cats
            elsif self.is_a?(Cat) && @size == "Big"
              # Big cats jump higher that people or dogs:

        class Person
          include Jump

          # rest of Person code ...

        class Animal
          include Jump

          # rest of Animal code ...

        class Dog < Animal
          # rest of Dog code ...

        class Cat < Animal
          # rest of Cat code ...

        cat = color: "White"
        dog = size: "Big"
        p "Cat's color: #{cat.color}"
        p "Cat can jump on a #{cat.jump_height} cm height"
        p "Dog's color: #{dog.color}"
        p "Dog can jump on a #{dog.jump_height} cm height"

        john = name: "John"
        john.learn "Ruby"
        john.learn "Python"
        john.learn "JavaScript"
        p "#{} can also jump on a #{john.jump_height} cm height"

The code should be pretty easy to understand, we did not change a lot here: We have added a new module with method jump_height 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 to print jump_height 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.

Book Index | Next