RbRuby

Ruby: Advanced – code examples

Contents

Pattern Matching with case/in

Advanced#pattern matching#case in#hash
Use case: Evaluate JSON responses or messages of different shapes.
def auswerten(antwort)
  case antwort
  in { status: "ok", daten: [erstes, *] }
    "First element: #{erstes}"
  in { status: "ok", daten: [] }
    "No data"
  in { status: "fehler", meldung: }
    "Error: #{meldung}"
  end
end
puts auswerten({ status: "ok", daten: [7, 8] })
puts auswerten({ status: "ok", daten: [] })
puts auswerten({ status: "fehler", meldung: "Timeout" })

Stable since Ruby 3.0. The pattern checks structure and values and binds variables (erstes, meldung). Without a matching pattern and without else, a NoMatchingPatternError occurs.

method_missing and define_method

Advanced#metaprogramming#method_missing#dsl
Use case: Build flexible APIs and DSLs, e.g. dynamic finders or configuration objects.
class Konfig
  def initialize
    @werte = {}
  end

  def method_missing(name, *args)
    if name.to_s.end_with?("=")
      @werte[name.to_s.chomp("=").to_sym] = args.first
    elsif @werte.key?(name)
      @werte[name]
    else
      super
    end
  end

  def respond_to_missing?(name, include_private = false)
    name.to_s.end_with?("=") || @werte.key?(name) || super
  end
end

k = Konfig.new
k.port = 8080
puts k.port, k.respond_to?(:port), k.respond_to?(:host)

method_missing intercepts unknown method calls; respond_to_missing? makes sure respond_to? answers correctly. Output: 8080, true, false. Use this sparingly.

Lazy Enumerator

Advanced#lazy#enumerator#streaming
Use case: Process huge or infinite sequences without holding everything in memory (e.g. large log files).
quadrate = (1..Float::INFINITY).lazy.select(&:even?).map { |x| x * x }
puts quadrate.first(4).inspect

zeilen = File.foreach("/etc/hosts").lazy
puts zeilen.reject { |z| z.start_with?("#") }.map(&:strip).first(2).inspect

lazy only evaluates the chain when first or to_a asks for values. The first output is [4, 16, 36, 64]. The file /etc/hosts exists on Unix systems; the second output depends on your system.