Skip to content

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.

Everything is an object; a class is an object too, an instance of Class, which is an instance of Module. Instances hold state in @variables; behaviour comes from the ancestor chain: singleton class, prepended modules, the class, included modules (last included first), superclasses, then Object, Kernel, BasicObject. Modules give mixins because they sit in that chain. Polymorphism is duck typing: if it responds to the message, it fits. self is the current receiver.

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
end
end
Account.new("Ada", 10).deposit(5).balance # => 15

initialize is private and called by new: new allocates, calls initialize, returns the object.

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.

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)".

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.

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"; end
module B; def label = "B"; end
class Order
include A
include B
end
Order.new.label # => "B" — the last included module wins
Order.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.

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.

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 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) || super
end
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.

  1. Given three modules and a superclass, what does ancestors return, and which foo runs?
  2. What is the difference between include, extend and prepend?
  3. Why is self.foo allowed for private methods, and what changed?
  4. When would you use method_missing instead of define_method?
  • Assuming include order does not matter. The last included module wins.
  • Forgetting super forwards all arguments.
  • Class variables leaking into subclasses. @@count is shared.
  • Defining two methods with the same name to “overload”. The second replaces the first.
  • method_missing without super. Every typo becomes nil instead of NoMethodError.