Tbpgr Blog

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

Ruby | Numeric | div

概要

Numeric#div(other) -> Integer

詳細

self を other で割った整数の商 q を返却。

div は内部的には Numeric の継承先で実装される 「/」メソッド
呼び出している。

サンプルコード
p 3.div(2)
p 3 / 2
p 4.div(2)
p 2.div(4)

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 /(other)
    # わざと商ではない計算を設定してみる
    @num + other.num
  end
end

# self.num + other.num = 6 が返却される
p EvenNumber.new(4).div(EvenNumber.new(2))

出力

$ ruby numeric_div.rb
1
1
2
0
6