!Mac OS X-10.15.7 !ruby-2.7.1p83
Rubyでフィボナッチ数列
フィボナッチ数列
フィボナッチ数列は以下の漸化式からなる.
F(0)=0
F(1)=1
F(n+2)=F(n)+F(n+1) (n>=0)
0,1,1,2,3,5,8,13,21...
コード
メインコードはこれ
require './assert_equal_richer_output.rb'
def fib(n)
return 0 if n==0
return 1 if n==1
return fib(n-1)+fib(n-2)
end
[[0,0],[1,1],[2,1],[3,2],[4,3],
[5,5],[6,8],[7,13],[8,21],[9,34]
].each do |index,expected|
puts assert_equal(expected,fib(index))
end
前回のassert_equal_richer_outputのコードはこれ
require 'colorize'
def assert_equal expected, result
p ['expected',expected]
p ['result',result]
if expected==result
puts 'true'.cyan
else
puts 'false'.magenta
end
end
if $PROGRAM_NAME == __FILE__
assert_equal(1,1)
assert_equal(1,2)
end
class
コードは以下
class Hello
def initialize
@name = gets_name
puts_hello
end
def puts_hello
puts "Hello #{@name}."
end
def gets_name
name = ARGV[0] || 'world'
return name
end
end
Hello.new
"@name"でnameを暮らす変数にする.
folding
emacsの場合C-c,h>>>folding
C-c,s>>>表示
- source ~/grad_members_20f/members/Kenny0704/c10.org