[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[dennou-ruby:000092] Re: operator redefinition



���Ȥ���Ǥ�

In message "[dennou-ruby:000091] operator redefinition"
    on 99/09/08, Takeshi Horinouchi <horinout@xxxxxx> writes:
>�Ȥ����ǥ��ڥ졼�����������
>
>  self + �ʤ�Ȥ�
>
>�ϤǤ���ΤǤ�����
>
> �ʤ�Ȥ� + self
>
>��������뤤����ˡ�ʤ��Ǥ����͡��֤ʤ�Ȥ��פˤʤꤦ�륯�饹
>�Ǻ�������뤷���ʤ������������

���äȡ�Numeric �Υ��֥��饹�ϼ�ʬ���Τ�ʤ����ڥ��ɤ��餦�ȡ�����
���ɤˡ�ʬ����褦���Ѵ����ơפ���ߤޤ������Υ᥽�åɤ� coerce �Ȥ�
���ޤ��������������ʬ����󤫤⤷��ޤ��󤬡����޻��֤ʤ��Τǡ��Ȥꤢ
�����������ޤ���ʬ����󤫤ä���ޤ�ʹ���Ʋ�������
# ��������ɤߤޤ��ΤǤ��Ф����Ԥ���!!

class Foo < Numeric
  class << self
    # Numeric �� new �ϻ����ʤ��Τ� new �򱣤�
    def [](val = 0.0)
      if val.kind_of?(Foo)
	val
      else
	new(val)
      end
    end

    private :new
  end

  def initialize(val = 0.0)
    @xxxxxx = val.to_f
  end
  attr_reader :val

  def +(other)
    if other.kind_of?(Float) || other.kind_of?(Integer)
      Foo[@xxxxxx + other]
    elsif other.kind_of?(Foo)
      Foo[@xxxxxx + other.val]
    else
      x,y = other.coerce(self)
      x + y
    end
  end

  def coerce(other)
    if other.kind_of?(Float) || other.kind_of?(Integer)
      return self, other
    else
      super
    end
  end
end

foo = Foo[100]
bar = Foo[200]
p foo + bar
p foo + 1
p 2 + bar
p 3.4 + foo