Duck typing and core idioms

If it quacks

Duck typing means Ruby cares about methods, not class names. If an object responds to quack, the caller treats it as a duck.

This keeps code flexible: new classes work with old methods without any shared parent. Collections of such objects are easy to process with Enumerables.

def greet(thing) puts "Hello, " + thing.to_s end greet("Ada") greet(42)

ruby duck_demo.rb

Hello, Ada
Hello, 42

To_s and inspect

to_s gives the friendly reading form: the text you show to users. inspect gives the programmer form with extra marks like quotes.

puts calls to_s, while p calls inspect. During debugging, p shows you the real structure.

name = "Ada" text = name.to_s puts text p name

ruby to_s_demo.rb

Ada
"Ada"

Comparable and sorting

Include Comparable and define <=> to gain sorting and all six comparison checks from one definition.

The method returns minus one, zero, or plus one depending on order. sort uses it automatically.

class Size include Comparable attr_reader :cm def initialize(cm) @cm = cm end def <=>(other) @cm <=> other.cm end end puts Size.new(3) < Size.new(9)

ruby comparable_demo.rb

true

Freeze constants

Constants can still change inside when they point to arrays or strings. Freeze them so accidental edits raise an error instead of corrupting state.

Capitalized names warn on reassignment but do not lock the object. Only freeze locks the content.

COLORS = ["red", "blue"].freeze begin COLORS << "green" rescue FrozenError => e puts e.message end p COLORS

ruby freeze_demo.rb

can't modify frozen Array: ["red", "blue"]
["red", "blue"]

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does duck typing mean in Ruby?

    Answer

    The caller cares about the methods an object answers, not its class

    If an object responds to quack, the caller treats it as a duck.

  2. What does this program print? def greet(thing) puts "Hello, " + thing.to_s end greet(42)

    Answer

    Hello, 42

    to_s turns the number into the text puts needs, so no class check is necessary.

  3. What does this program print? name = "Ada" text = name.to_s puts text p name

    Answer

    Ada / "Ada"

    puts uses to_s, p uses inspect, which keeps the quotes around a string.

  4. What does including Comparable and defining <=> give a class?

    Answer

    All six comparison checks and sorting from one definition

    Comparable builds <, <=, ==, >=, > and between? on top of <=>.

  5. What does this program print? class Size include Comparable attr_reader :cm def initialize(cm) @cm = cm end def <=>(other) @cm <=> other.cm end end puts Size.new(3) < Size.new(9)

    Answer

    true

    Comparable defines < from <=>, and 3 is smaller than 9.

  6. What does this program print? class Size include Comparable attr_reader :cm def initialize(cm) @cm = cm end def <=>(other) @cm <=> other.cm end end p [Size.new(9), Size.new(3)].sort.map(&:cm)

    Answer

    [3, 9]

    sort uses <=> and puts the smaller object first.

  7. What does this program print? COLORS = ["red", "blue"].freeze begin COLORS << "green" rescue FrozenError => e puts e.class end

    Answer

    FrozenError

    A frozen array refuses a modification with FrozenError.

  8. Which call does p use to show a value?

    Answer

    inspect

    p uses inspect, which is why a string keeps its quotes and a structure keeps its shape.

  9. A constant A = [1].freeze is followed by A = [2]. What happens?

    Answer

    A warning on reassignment, and A points at the new array

    freeze locks the object, not the name: reassigning the constant only warns.

  10. What does this program print? def greet(thing) thing.to_s end p greet(:a)

    Answer

    "a"

    to_s turns :a into "a", and p prints that string with its quotes.

Article author: Arthur Isaev