On Nov 4, 4:52=A0am, Daniel Vartanov <daniel.varta... / gmail.com> wrote:
> 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
> =A0 def +(object)
> =A0 =A0 super(object) unless object.kind_of?(Vector)
>
> =A0 =A0 # vector-number multiplication here...
> =A0 end
> end
>
> But, of course, we need a replacement here. How to implement it?

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

  =A0 =A0 # vector-number multiplication here...
  end

But maybe better something like:

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

    alias_method :_plus, :+

    def +(operand)
      if procedure =3D 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.