A module is a collection of processes.
#Example: Caluculate module that summarizes addition and subtraction processing
module Calculate
def add(a, b)
a + b
end
def sub(a, b)
a - b
end
end
Modules and classes are similar, but with the following differences:
The module is used for the following purposes.
The same class can be used as a different class by putting it in a module with a different name.
#Example: Include the same Image class in another module and different classes (User)::Image and Post::Treat as Image)
module User
class Image
def self.hoge
puts 'user image'
end
end
end
module Post
class Image
def self.hoge
puts 'post image'
end
end
end
User::Image.hoge #=> "user image"
Post::Image.hoge #=> "post image"
You can use the include method to include the module processing as an instance method of the target class.
#Example: Incorporate User module as an instance method of Image class
module User
def hoge
puts 'user image'
end
end
class Image
include User
end
image = Image.new
image.hoge #=> "user image"
You can use the extend method to import the module processing as a class method of the target class.
#Example: Incorporate User module as class method of Image class
module User
def hoge
puts 'user image'
end
end
class Image
extend User
end
Image.hoge #=> "user image"
Recommended Posts