!Mac OS X-10.15.7 !ruby-2.7.1p83
Recursive Fibonacci
講義ページリンク
チャート式ruby-V(Recursive Fibonacci)
内容
rubyで再帰処理
課題
フィボナッチ数列を計算するプログラムの作成
解答例
"assert_equal.rb"
#!/usr/bin/env ruby
# frozen_string_literal: true
def fib(n)
if n.zero?
0
elsif n == 1
1
else
fib(n - 1) + fib(n - 2)
end
end
require './assert_equal'
[[0, 0], [1, 1], [2, 1], [3, 2], [4, 3],
[5, 5], [6, 8], [7, 13], [8, 21]].each do |index, expected|
puts assert_equal(expected, fib(index))
end
出力
> ruby fibonacci.rb
expected: 0
result: 0
succeeded in assert_equal.
expected: 1
result: 1
succeeded in assert_equal.
expected: 1
result: 1
succeeded in assert_equal.
expected: 2
result: 2
succeeded in assert_equal.
expected: 3
result: 3
succeeded in assert_equal.
expected: 5
result: 5
succeeded in assert_equal.
expected: 8
result: 8
succeeded in assert_equal.
expected: 13
result: 13
succeeded in assert_equal.
expected: 21
result: 21
succeeded in assert_equal.
NOTE
- 再帰処理は他のプログラミング言語と同じように書ける
- rubocopいわくfibというmethod名は短いらしいけど特に問題ないので無視する
- source ~/multiscalesim_toku/grad_members_20f/members/lynd2299/mss10.org