Created
August 20, 2011 12:58
-
-
Save pasberth/1159074 to your computer and use it in GitHub Desktop.
case-when のようなものを作ってみた
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- 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