What does 'extend self' mean in Ruby?
I came across the following in Pagy’s code base:
class Pagy
module I18n
extend self # what does this mean?
end
end
What does extend self
mean?
You can think about extend
as opening up the eigenclass (or singleton class) of a particular object.
In this case, we are opening the singleton class of the I18n
module and adding the methods in I18n to itself. If that is confusing, consider the following example:
module Car
extend self
def drive
puts "Don't stop me now! I'm having such a good time, havin' a ball!"
end
end
class Toyota
include Car
end
t = Toyota.new
t.drive
# => Don't stop me (driving)! I'm having such a good time, havin' a ball!
Car.drive
# => Don't stop me (driving)! I'm having such a good time, havin' a ball!
# extend self makes the above possible.
Quiz: Will this work?
Let’s test your knowledge:
# Let's go one step further:
Toyota.drive # will this work? What do you think?
If that won’t work, what will you need to do in order to make it work?
Hint: extend yourself - in finding the answer.
class Toyota
extend Car
end
Toyota.drive # now will it work?
Written on January 25, 2024