It is a module that is a function of Ruby, but I feel that it is one of the parts that is difficult to understand for those who are new to Ruby.
So this time I will summarize the modules.
● Mixins (include and extend) ● Creating namespaces ● Provide functions and methods
There are other features, but I've listed three main ones. Today I would like to take a look at these.
I don't know what it means to be a mixin, Multiple inheritance can be done by incorporating the module into the class. In Ruby, only single inheritance of class is possible, but module can be multiple inheritance. Also, unlike class, the same function can be shared even if it is not an is-a relationship (a relationship that an object is "an instance of a class or its descendant class").
Addendum: The explanation of the is-a relationship has been corrected. Thank you for your comment.
include
ruby.rb
module Hoge
def hello
puts 'Hello'
end
end
module Bar
def bye
puts 'Bye'
end
end
class Greet
#Include the module created above
include Hoge
include Bar
end
greet = Greet.new
greet.hello #=> "Hello"
greet.bye #=> "Bye"
By including as above, the class can use the methods defined in the module. Adding a function by including a module in a class in this way is called a mixin.
extend You can use extend to turn a method in a module into a class method.
ruby.rb
module Hoge
def hello
puts 'Hello'
end
end
class Greet
#Extend the module created above
extend Hoge
end
#You can call hello as a class method
Greet.hello #=> "Hello"
Like this, you can use the methods defined in the module with include or extend in the class. It is a mixin that is one of the ways to use the module.
If you write a class in the module name, it means a class that belongs to the module. You can prevent name conflicts.
module Bar
class Baz
def self.foo
puts 'foo'
end
end
end
#I called the foo method from the Baz class that belongs to the module called Bar.
Bar::Baz.foo #=> "foo"
What I felt after working as an engineer There are many opportunities to use namespaces. Because the bigger the project, the more risky name conflicts will occur. We often set namespaces in this way to prevent collisions.
Constants defined in the module can be called via the module name.
ruby.rb
module Hoge
Year = "2020"
end
Hoge::Year #=> "2020"
Instance methods can be called by using the module_function method and making the method a module function.
ruby.rb
module Hoge
def hello
puts 'Hello'
end
module_function :hello
end
Hoge.hello #=> "Hello"
That concludes the module summary. Today was the 10th day of the serialization of an engineer who will become a full-fledged engineer 100 days later.
** 90 days to become a full-fledged engineer **
Recommended Posts