Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created August 20, 2011 12:58
Show Gist options
  • Select an option

  • Save pasberth/1159074 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/1159074 to your computer and use it in GitHub Desktop.
case-when のようなものを作ってみた
# -*- coding: utf-8 -*-
module Kernel
def match(obj, &blk)
b = binding
def b.if_that_is *something, &doing
unless @matchers
@matchers = {}
@matchers.default = proc { nil }
end
something.each { |e|
@matchers[e] = doing
}
end
def b.or_else &doing
@matchers ||= {}
@matchers.default = doing
end
def b.method_missing funcname, *args
$temporary_args = args
if $temporary_args.empty?
ret = eval "#{funcname}"
else
ret = eval "#{funcname}(*$temporary_args)"
end
$temporary_args = nil
ret
end
b.instance_eval(&blk)
b.send(:instance_variable_get, :@matchers)[obj].call
end
end
if __FILE__ == $PROGRAM_NAME
require "test/unit"
class TestMatch < Test::Unit::TestCase
def setup
end
def test_numbers
res = nil
match(5) {
if_that_is(1, 2, 3) {
res = false
}
if_that_is(4, 5) {
res = true
}
}
assert res
end
def test_strings
res = nil
match("Medli") {
if_that_is("Medli") {
res = true
}
if_that_is("Komali") {
res = false
}
}
assert res
end
def test_regexp
res = nil
match("Medli") {
if_that_is(/^Me.li$/) {
res = true
}
or_else {
res = false
}
}
assert res
end
def test_or_else
res = nil
match("Medli") {
if_that_is("Komali") {
res = false
}
or_else {
res = true
}
}
assert true
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment