るりまサーチ

最速Rubyリファレンスマニュアル検索!
11件ヒット [1-11件を表示] (0.069秒)

別のキーワード

  1. _builtin new
  2. _builtin inspect
  3. _builtin []
  4. _builtin to_s
  5. _builtin each

ライブラリ

検索結果

Numeric#coerce(other) -> [Numeric] (35240.0)

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

...her を Float に変換して [other, self] という配列にして返します。
Numeric
のサブクラスは、このメソッドを適切に再定義しなければなりません。
以下は Rational の coerce のソースです。other が自身の知らない数値クラスであった場...
...合、
super を呼んでいることに注意して下さい。


//emlist[例][ruby]{
# 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
//}

数値...
...以下は Rational の + メソッドを一部省略したものです。
引数が自身の知らない数値クラスである場合、引数の coerce により自身を変換してから
+ 演算子を呼んでいます。

//emlist[例][ruby]{
# lib/rational.rb より

def + (a)
if a.kind_of...