Created
November 26, 2015 02:43
-
-
Save osyo-manga/8260478a958dc28065db to your computer and use it in GitHub Desktop.
momonga
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
| module ArrayEx | |
| refine Array do | |
| def === other | |
| each_with_index do |it, index| | |
| return false unless it === other[index] | |
| end | |
| true | |
| end | |
| end | |
| end | |
| using ArrayEx | |
| module Stitcher | |
| def register name, sig, &block | |
| mem = instance_method(name) | |
| return register(name, sig, &proc { |*args| mem.bind(self).call *args }) unless block_given? | |
| include(Module.new do | |
| define_method name do |*args| | |
| return super(*args) unless sig === args | |
| instance_exec *args, &block | |
| end | |
| end) | |
| define_method name do |*args| | |
| super(*args) | |
| end | |
| end | |
| end | |
| class X | |
| extend Stitcher | |
| def initialize | |
| end | |
| def plus a, b | |
| p "Fixnum, Fixnum" | |
| end | |
| register :plus, [Fixnum, Fixnum] | |
| def plus a, b | |
| p "String, String" | |
| end | |
| register :plus, [String, String] | |
| def plus a, b | |
| p "String, Fixnum" | |
| end | |
| register :plus, proc { |a, b| String === a && Fixnum === b } | |
| register :plus, [Fixnum, String] do |a, b| | |
| p "Fixnum, String" | |
| plus 1, 2 | |
| end | |
| end | |
| p X.ancestors | |
| # => [X, #<Module:0x0000000222ef78>, #<Module:0x0000000222f180>, #<Module:0x0000000222f400>, #<Module:0x0000000222f658>, Object, Kernel, BasicObject] | |
| x = X.new | |
| x.plus 1, 2 | |
| x.plus "", "" | |
| x.plus "", 1 | |
| x.plus 1, "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment