Skip to content

Instantly share code, notes, and snippets.

@scalp42
Forked from evanphx/check.rb
Last active August 28, 2015 20:58
Show Gist options
  • Save scalp42/87f91019588428b3311e to your computer and use it in GitHub Desktop.
Save scalp42/87f91019588428b3311e to your computer and use it in GitHub Desktop.
Ruby "type" checking
def foo(a : String)
# the method prologue is injected with
raise TypeError unless String === a
end
# Allows for other interesting ones, like:
def use_as_number(a : /\d+/)
end
# and more interesting
class RespondTo
def initialize(method)
@method = method
end
def ===(o)
o.respond_to? @method
end
end
ToS = RespondTo.new(:to_s)
def stringy(s : ToS)
# same prologue as before, now doing a respond_to check.
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment