2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

フィボナッチ数列

Last updated at Posted at 2020-11-29

!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
2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?