Ruby 4.0 リファレンスマニュアル

instance method Numeric#coerce

coerce(other) -> [Numeric][permalink][rdoc][edit]
(Numeric) → [ Numeric, Numeric ]

selfother が同じクラスになるよう、selfother を変換し [other, self] という配列にして返します。

デフォルトでは selfotherFloat に変換して [other, self] という配列にして返します。

Numeric のサブクラスは必要に応じてこのメソッドを適切に再定義しなければなりません。

以下は Rationalcoerce のソースです。other が自身の知らない数値クラスであった場合、super を呼んでいることに注意して下さい。

# lib/rational.rb より

def coerce(other)
  if other.kind_of?(Float)
    return other, self.to_f
  elsif other.kind_of?(Integer)
    return Rational.new!(other, 1), self
  else
    super
  end
end

数値クラスの算術演算子は通常自分と演算できないクラスをオペランドとして受け取ると coerce を使って自分とオペランドを変換した上で演算を行います。以下は Rational+ メソッドを一部省略したものです。引数が自身の知らない数値クラスである場合、引数の coerce により self を変換してから + 演算子を呼んでいます。

# lib/rational.rb より

def + (a)
  if a.kind_of?(Rational)
    # 長いので省略
  elsif a.kind_of?(Integer)
    # 長いので省略
  elsif a.kind_of?(Float)
    Float(self) + a
  else
    x, y = a.coerce(self)
    x + y
  end
end
[PARAM] other:
オペランドを数値で指定します。