Tail_recursion.rb

This content was produced by an LLM and could include errors.

このスクリプトは1からnまでの総和を求めます。ファイル名に反して再帰呼び出しは使わず、while ループで末尾再帰相当の処理を書き換えた形になっています(Rubyは末尾呼び出し最適化を保証しないため)。sum(10) は 1+2+…+10 の 55 を出力します。

# frozen_string_literal: true
#=> nil

def sum(n)
  m = 0
  while n != 1
    m += n
    n -= 1
  end
  m + 1
end
#=> :sum

puts sum(10)
55
#=> nil

Ruby 4.0.6