nilはクラスであり、メソッドの使用ができる

sum関数でエラーがでた

下記のメソッドを使いたいとします。

def calc_score
    [@first_shot.point, @second_shot.point, @third_shot.point].sum
  end

インスタンスはこうやって作られます。

def initialize(first_shot, second_shot = nil, third_shot = nil)
    @first_shot = Shot.new(first_shot)
    @second_shot = Shot.new(second_shot)
    @third_shot = Shot.new(third_shot)
  end


インスタンスのShotクラスの実装はこうです。

class Shot
  attr_reader :point

  def initialize(pinfall)
    @point = pinfall
  end
end


この実装だと、

in `+': nil can't be coerced into Integer (TypeError)

と怒られてしまいます。

nilにもメソッドがある


docs.ruby-lang.org


まず結論から。
上記のエラーを無くす方法は、

class Shot
  attr_reader :point

  def initialize(pinfall)
    @point = pinfall.to_i
  end
end

to_iのメソッドを使用します。

今回sumメソッドのエラーの原因は、
(TypeError)です。
そのままの意味で、nilとの型の不一致です。
Rubyはすべてがインスタンス扱いです。ゆえに

docs.ruby-lang.org

nilクラスがあり、メソッドもあります。
to_iを行い0を返すことで、エラー解消となります。

ちなみに、

def initialize(first_shot, second_shot = nil, third_shot = nil)


ここで初期値設定していますが、もとはArgumentError: wrong number of arguments (given 2, expected 3)対策でした。
ですがその後の実装によって、
・そもそも設定せずともエラーがでない
・例えば、0にしても結局nilになって返ってくる
などあり、こちらについてはもう少し調査したいと思います。

以上です。