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
end
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
50
elsif self.is_a?(Dog) && @size == "Small"
# small dogs don't usually jump very high
30
elsif self.is_a?(Dog) && @size == "Medium"
# medium dogs don't can jump higher that a human sometimes
60
elsif self.is_a?(Dog) && @size == "Big"
# big dogs can jump twice as high as a small dogs
80
elsif self.is_a?(Cat) && @size == "Small"
# I believe small cats can jump higher that dogs. What do you think?
40
elsif self.is_a?(Cat) && @size == "Medium"
# Same for medium cats
70
elsif self.is_a?(Cat) && @size == "Big"
# Big cats jump higher that people or dogs:
90
end
end
end
class Person
include Jump
# rest of Person code ...
end
class Animal
include Jump
# rest of Animal code ...
end
class Dog < Animal
# rest of Dog code ...
end
class Cat < Animal
# rest of Cat code ...
end
cat = Cat.new color: "White"
dog = Dog.new size: "Big"
p "Cat's color: #{cat.color}"
p "Cat can jump on a #{cat.jump_height} cm height"
cat.make_sound
p "Dog's color: #{dog.color}"
p "Dog can jump on a #{dog.jump_height} cm height"
dog.make_sound
john = Person.new name: "John"
john.learn "Ruby"
john.learn "Python"
john.learn "JavaScript"
john.resume
p "#{john.name} 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.