Module: Ov::Ext

Defined in:
lib/ov/ext/matching.rb

Instance Method Summary collapse

Instance Method Details

#match(*args, &block) ⇒ Object

Add ‘match` method, which work like `case` statement but for types

Usage

include Ov::Ext    

match("String", "dsa") do 
  try(String, Array) {|str, arr| "#{str} #{arr}" }
  try(String) {|str| "#{str}"  }
  otherwise { "none" }
end


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ov/ext/matching.rb', line 17

def match(*args, &block)
  z = Module.new do 
    include Ov
    extend self
    def try(*args, &block)
      let :anon_method, *args, &block
    end
    def otherwise(&block)
      let :otherwise, &block
    end
    instance_eval &block
  end
  begin
    z.anon_method(*args)
  rescue Ov::NotImplementError => e 
    z.otherwise
  end  
end