Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Numeric | coerce

概要

Numeric#coerce(other) -> [Numeric]

詳細

self と other が同じクラスになるよう、自身か other を変換し [other, self] という配列にして返却。
Number クラスのサブクラスを新たに定義する際に、実装が必要となる。
デフォルトは Float に変換。

coerce = 強要する

サンプルコード
p 1.coerce(1.1)
p 1.1.coerce(1)
p 1.coerce("111")

class EvenNumber < Numeric
  attr_reader :num

  def initialize(num)
    @num = num
    @num += 1 if @num.odd?
  end

  def normalize
    @num += 1 if @num.odd?
  end

  def coerce(other)
    other = Integer(other)
    [self, EvenNumber.new(other)]
  end
end

p EvenNumber.new(2).coerce(1)
p EvenNumber.new(2).coerce(4)

出力

$ ruby numeric_coerce.rb
[1.1, 1.0]
[1.0, 1.1]
[111.0, 1.0]
[#<EvenNumber:0x0000060045f488 @num=2>, #<EvenNumber:0x0000060045f460 @num=2>]
[#<EvenNumber:0x0000060045f258 @num=2>, #<EvenNumber:0x0000060045f230 @num=4>]