LoginSignup
1
0

More than 3 years have passed since last update.

授業メモ6

Last updated at Posted at 2020-12-31

再帰

 そもそも再帰とは関数や計算式の中で自身と同じ関数を用いること. これにより,関数を複数定義したものよりも簡単にコードを書くことができる.

再帰の利用

 今回,再帰の利用としてフィボナッチ数列を用いる.

 フィボナッチ数列は初項0,第1項が1であり,n項+n+1項がn+2項になるような数列である. この数列は前の項を次々に参照してつながっていくため,再帰が利用できそうである.

 初項と第1項は定義しておかないと求めることができないので,

def fib(n)

if n == 0

return 0

end

if n == 1

return 1

end

end

 これで初項と第1項を定義することができた.

 次は第1項以降の定義を追加する.

return fib(n - 1) + fib(n - 2)

 上記の式を追加する.

 最後にテストをするための配列を作る.

[[6,8],[7,13],[8,21]].each do |index, expected|

printf assert equal(expected,fib(index))

end

 これでフィボナッチ数列を再帰を用いて表すことができた.

class化

 隠ぺい,継承,多形をさらに言語のシステムとして徹底したものがclassというものらしい.

 授業メモ3でやった出力方法,Hello worldを少し変えたものを使ってみる.

def putshello name

puts "Hello #{name}."

end

def getsname

name = ARGV[0] || 'world'

return name

end

name = getsname

putshello name

 この中のループを消してしまおうというのがclassとしての考えなようです. これに対してrefactoringを行う.

class Greeter

def initialize

@name = getsname

putshello

end

def putshello #salute

puts "Hello #{@name}."

end

def getsname

name = ARGV[0] || 'world'

return name.capitalize

end

end

Greeter.new

 これでも結果が同じになりました.


  • source ~/grad_members_20f/members/adchello/test5.org
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0