Object Orientation in Ruby
Ruby’s object model is unusually explicit: classes are objects, self changes meaning with context,
and method lookup walks a linear ancestor chain that includes modules. Interviewers use this topic
because the answers are checkable.
The 60-second answer
Section titled “The 60-second answer”Everything is an object; a class is an object too, an instance of
Class, which is an instance ofModule. Instances hold state in@variables; behaviour comes from the ancestor chain: singleton class, prepended modules, the class, included modules (last included first), superclasses, thenObject,Kernel,BasicObject. Modules give mixins because they sit in that chain. Polymorphism is duck typing: if it responds to the message, it fits.selfis the current receiver.
Classes and objects
Section titled “Classes and objects”class Account attr_reader :owner attr_accessor :balance
def initialize(owner, balance = 0) = (@owner, @balance = owner, balance)
def deposit(amount) raise ArgumentError, "amount must be positive" unless amount.positive? @balance += amount self # return self to allow chaining endend
Account.new("Ada", 10).deposit(5).balance # => 15initialize is private and called by new: new allocates, calls initialize, returns the object.
Instance vs class methods
Section titled “Instance vs class methods”A class method is a method on the class object. def self.name is idiomatic; class << self opens
the singleton class, where class methods live. @@count is a class variable, shared with
subclasses and usually a smell.
Inheritance
Section titled “Inheritance”class Puppy < Dog inherits methods and the @variable layout. Ruby has single inheritance only.
super with no parentheses forwards the current arguments; super() forwards none; super(x)
forwards x — so def speak = "Yip (#{super})" in Puppy < Dog yields "Yip (Woof)".
Modules and mixins
Section titled “Modules and mixins”A module cannot be instantiated. It namespaces constants and mixes behaviour into the ancestor chain.
| Keyword | Effect | Placement |
|---|---|---|
include M |
Instance methods | Between the class and its superclass |
prepend M |
Instance methods | Ahead of the class |
extend M |
Singleton methods | The object’s singleton class |
A module method that calls super composes with the class’s own method: prepend Auditable puts
Auditable#save ahead of Employee#save, so it can log then super. extend is just include on
the singleton class — that is the whole trick.
Method lookup
Section titled “Method lookup”For obj.m, Ruby searches the singleton class, prepended modules, the class, included modules (most
recent first), superclasses with their own modules, then Object, Kernel, BasicObject.
module A; def label = "A"; endmodule B; def label = "B"; end
class Order include A include Bend
Order.new.label # => "B" — the last included module winsOrder.ancestors # => [Order, B, A, Object, Kernel, BasicObject]ancestors answers almost every “which method gets called” question.
self is main at top level, the class inside a class body or class method, the instance inside an
instance method, and — inside a block — whatever it was where the block was defined. instance_eval
and class_eval exist to change it deliberately.
Visibility
Section titled “Visibility”public is the default. private means “no explicit receiver”, though self.foo is allowed since
Ruby 2.7. protected allows other instances of the same class to call the method.
Polymorphism and duck typing
Section titled “Polymorphism and duck typing”Ruby has no method overloading: a second definition with the same name replaces the first. Ad-hoc
polymorphism is redefinition in subclasses; parametric comes from duck typing rather than generics;
subtype is a subclass used where the parent is expected. Prefer def log(message) = puts(message.to_s)
over an is_a?(String) guard, and pair duck typing with fast tests rather than respond_to? checks.
method_missing
Section titled “method_missing”method_missing intercepts calls to undefined methods — powerful for proxies and DSLs, expensive to
debug: class Settings below exposes hash keys as methods.
class Settings def initialize(data) = @data = data def method_missing(name, *args) = @data.key?(name) ? @data[name] : super def respond_to_missing?(name, include_private = false) = @data.key?(name) || superend
Settings.new(theme: "dark").theme # => "dark"Always call super and always implement respond_to_missing?, or every typo silently becomes nil.
Prefer define_method when the names are known: faster and introspectable.
Follow-up questions
Section titled “Follow-up questions”- Given three modules and a superclass, what does
ancestorsreturn, and whichfooruns? - What is the difference between
include,extendandprepend? - Why is
self.fooallowed for private methods, and what changed? - When would you use
method_missinginstead ofdefine_method?
Common traps
Section titled “Common traps”- Assuming
includeorder does not matter. The last included module wins. - Forgetting
superforwards all arguments. - Class variables leaking into subclasses.
@@countis shared. - Defining two methods with the same name to “overload”. The second replaces the first.
method_missingwithoutsuper. Every typo becomesnilinstead ofNoMethodError.