πŸŽ“ A1Learner
πŸ”
0 of 28 lessons completed

Ruby Advanced Introduction

This course goes to the deepest parts of Ruby. It builds on the intermediate course, where you met method_missing, modules and class methods.

A class method with def self.

Shelter defines motto with def self. in front of its name. The class itself answers the call.

class Shelter
  def self.motto
    puts "Every dog counts"
  end
end
Shelter.motto

A fallback with method_missing

Echo defines no whistle method. method_missing receives the unknown name and prints a line with it.

class Echo
  def method_missing(name, *args)
    puts "No method called #{name}"
  end
end
echo = Echo.new
echo.whistle

A module mixed into a class

Friendly holds one greet method. Cat mixes Friendly in with include, so a cat object can call greet.

module Friendly
  def greet
    puts "Hello there"
  end
end
class Cat
  include Friendly
end
cat = Cat.new
cat.greet

Example

class Dog
  def method_missing(name, *args)
    puts "Dog cannot #{name}"
  end
end
dog = Dog.new
def dog.speak
  puts "Woof once"
end
dog.speak
dog.dance

Key points

  • Singleton classes give each object a class of its very own.
  • Evaluation tools build methods and run blocks against chosen objects.
  • Pattern matching checks the shape of a value and binds its parts.
  • Fibers pause work in one place, and ractors run work in parallel.
  • Refinements change a class inside one small scope only.
  • Frozen objects lock their contents against change.
  • The course closes by building a small language of your own.

In this example, one dog gains a speak method of its own through a singleton method. The dance call finds no matching method, so method_missing answers it instead. The two lines show a known call and a fallback call side by side.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which shape defines a class method on Shelter itself?