Ruby_typed_methods

I got a little jealous of Raku’s typed methods.. so I spent half-an-hour writing this:

class Typed

  def initialize = ( @data, @leg = Struct.new(:type, :prc), {} )
  def define(&bl) = ( instance_exec(&bl) if bl )

  private
  def (main, sub, tp, prc)
    @leg[sub] = @data.new(tp, prc)
    @leg.key?(main) ? (@leg[main] << sub) : (@leg[main] = [sub]) 
  end

  def method_missing(name, *args, **kwargs)
    @leg[name].map { @leg[it] }.select { it.type == args.map(&:class) }.tap {
      it.empty? ? nil : it.first.prc.(*args, **kwargs)
    }
  end
end


# usage:

tp = Typed.new

tp.define {
   :add, :add_int, [Integer, Integer], proc {|a,b| puts "Sum: #{a+b}" }
   :add, :add_str, [String, String],   proc {|a,b| puts "Str: #{a} #{b}" }
}


tp.add(3, 7) #          Sum: 10
tp.add('ior', 'åsna') # Str: ior åsna
tp.add(3, 'olle')

I haven’t even tested it for real.. and there are things that are very ‘prototype solution’.

But ‘as is’ .. it redirects method calls depending on what type arguments are.