Introduction
Mixins let you share code between classes easily. Custom modules help you add useful features without repeating code.
Mixins let you share code between classes easily. Custom modules help you add useful features without repeating code.
module ModuleName def method_name # code here end end class ClassName include ModuleName end
module to create a module with methods.include inside a class to add module methods as instance methods.module Greet def say_hello puts "Hello!" end end class Person include Greet end p = Person.new p.say_hello
module MathHelpers def square(x) x * x end end class Calculator include MathHelpers end calc = Calculator.new puts calc.square(4)
This program shows how the Logger module adds a log method to the User class. When we call create, it logs a message.
module Logger def log(message) puts "LOG: #{message}" end end class User include Logger def create log("User created") end end user = User.new user.create
Modules cannot be instantiated like classes; they are only for sharing code.
Using include adds module methods as instance methods.
You can also use extend to add module methods as class methods.
Custom modules let you share methods across classes without repeating code.
Use include to add module methods as instance methods.
Mixins help keep your code organized and reusable.
Greetings inside a class Person?include inside the class to add module methods as instance methods.class Person; include Greetings; end is valid Ruby syntax for this purpose.module Talk
def speak
"Hello!"
end
end
class Dog
include Talk
end
puts Dog.new.speakTalk module defines speak method. Including it in Dog adds speak as an instance method.Dog.new.speak calls the method and returns "Hello!" string.module Helper
def help
"Helping"
end
end
class User
extend Helper
end
puts User.new.helpextend Helper adds methods as class methods, not instance methods.User.new.help calls help on an instance, but method is only on class, causing NoMethodError.Walk and Talk with methods walk and speak respectively, how can you create a class Person that uses both modules as mixins and calls both methods on an instance?
Choose the correct code snippet.include multiple times inside the class.p.walk and p.speak work.Pass the test and this pattern moves unknown