On Nov 4, 4:52 ¨Βν¬ Δαξιεμ Φαςταξοφ Όδαξιεμ®φαςτα®®®ΐηναιμ®γονχςοτεΊ
> Hello!
>
> I am trying to replace .+ operator of Numeric class if and only if
> argument (summand) is my own class.
>
> To be more specific: I am writing geometry module in Ruby and need to
> implement vector-number multiplication so that both:
>
> 2 * vector
> vector * 2
>
> work well.
>
> Therefore I need to replace .+ method of Numeric without spoiling
> arithmetical operations with other classes. It is clear, that in case of
> inheritance we can just write:
>
> class MyNumeric < Numeric
> def +(object)
> super(object) unless object.kind_of?(Vector)
>
> # vector-number multiplication here...
> end
> end
>
> But, of course, we need a replacement here. How to implement it?

  class Numeric
    alias_method :_plus, :+
  def +(vector)
  unless vector.kind_of?(Vector)
  return _plus(vector)
  end

  # vector-number multiplication here...
  end

But maybe better something like:

  class Numeric
    def self.op_map(op, klass=nil, &block)
      op = op.to_sym
      @op_map ||= {}
      @op_map[op] ||= {}
      return @op_map[op] unless klass
      return @op_map[op][klass] unless block
      @op_map[op][klass] = block
    end

    alias_method :_plus, :+

    def +(operand)
      if procedure = self.class.op_map[:+][operand.class]
        procedure.call(operand)
      else
        _plus(vector)
      end
    end
  end

  Numeric.op_map(:+,Vector) do |operand|
    # ... your vector addition here
  end

T.