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)

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.

n = 42 puts n.to_s p n

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)

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 APP = "aredel".freeze

Next: Struct and Data

Article author: Arthur Isaev