Skip to content

Instantly share code, notes, and snippets.

# =======================
# Spell: Pattern Dispatch
# =======================
# Select which methods to call based on their names.
$x = 0
class C
def my_first_method
@zzak
zzak / open_class.rb
Created September 13, 2010 16:53 — forked from nusco/open_class.rb
# =================
# Spell: Open Class
# =================
# Modify an existing class.
class String
def my_string_method
"my method"
end
# =======================
# Spell: Object Extension
# =======================
# Define Singleton Methods by mixing a module into an object’s eigenclass.
obj = Object.new
module M
def my_method
@zzak
zzak / nil_guard.rb
Created September 13, 2010 16:53 — forked from nusco/nil_guard.rb
# ================
# Spell: Nil Guard
# ================
# Override a reference to nil with an “or.”
x = nil
y=x || "avalue" # =>"avalue"
# For more information: http://www.pragprog.com/titles/ppmetr/metaprogramming-ruby
@zzak
zzak / namespace.rb
Created September 13, 2010 16:53 — forked from nusco/namespace.rb
# ================
# Spell: Namespace
# ================
# Define constants within a module to avoid name clashes.
module MyNamespace
class Array
def to_s
"my class"
# ======================
# Spell: Named Arguments
# ======================
# Collect method arguments into a hash to identify them by name.
def my_method(args)
args[:arg2]
end
@zzak
zzak / monkeypatch.rb
Created September 13, 2010 16:53 — forked from nusco/monkeypatch.rb
# ==================
# Spell: Monkeypatch
# ==================
# Change the features of an existing class.
"abc".reverse # => "cba"
class String
def reverse
# ===================
# Spell: Mimic Method
# ===================
# Disguise a method as another language construct.
def BaseClass(name)
name == "string" ? String : Object
end
# =============================
# Spell: Lazy Instance Variable
# =============================
# Wait until the first access to initialize an instance variable.
class C
def attribute
@attribute = @attribute || "some value"
end
# ====================
# Spell: Kernel Method
# ====================
# Define a method in module Kernel to make the method available to all objects.
module Kernel
def a_method
"a kernel method"
end