10/11 対象のモデル化とデータ構造(1)


スライドの補足


スライドに使われたプログラム

配列

days_of_each_month =   [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
days_of_each_month[1]
# 2月の日数はいくつかを訊く.0 origin (0から始めるということ)
something_of_each_month =
  [ true, true, true, true, false, false, false, false, true, true, true, true ]
something_of_each_month[10]
# 11月のほにゃららはどうかを訊く.
markov =
[ [0.3, 0.2, 0.5],
  [0.2, 0.5, 0.3],
  [0.6, 0.3, 0.1] ]

レコード(Struct)の例(1)

ComplexNumber = Struct.new(:realPart, :imaginaryPart)
zero = ComplexNumber.new(0, 0) # 0 + 0i
c = ComplexNumber.new(3, 4)      # 3 + 4i
c.realPart # . はフィールドアクセスの記法
RationalNumber = Struct.new(:numerator , :denominator)
r = RationalNumber.new(22, 7)     # 22/7
r.numerator

オブジェクトで定義した複素数

class ComplexNumber      # ComplexNumberというクラスの定義
   def initialize(x, y)             # 新しいComplexNumberオブジェクトの初期化
      @realPart = x               # @... は構造体のフィールドに相当するもの
      @imaginaryPart = y     # ここでは, realPartとimaginaryPartを定義
  end
  def realPart() @realPart end                      # 実数部を取り出すメソッド
  def imaginaryPart() @imaginaryPart end   # 虚数部を取り出すメソッド
  # ほかにも多数のメソッドが続く
end
c = ComplexNumber.new(3, 4)   # Structとまったく同じ形
c.realPart                                     # これも同様

メソッド

class ComplexNumber      # ComplexNumberというクラスの定義
   # … (前のページと同じところは省略)
  include Math                     # 数学ライブラリを使うという宣言
  def radius()                        # 複素数の絶対値,**はべき乗の意味
      sqrt(@realPart**2 + @imaginaryPart**2)
  end
  def argument()                   # 複素数の偏角 (ラジアン)
      # 自分で書いてみよう (tanの逆関数はatan)
  end
   # ほかにも四則演算等の多数のメソッドが続く
end
c = ComplexNumber.new(3, 4)
c.radius                                # 値は浮動小数点数になる

レコード(Struct)の例(2)

Date = Struct.new(:year, :month, :day)
special_day = Date.new(2000, "Febrary", 2)
tanaka_san_birthday = Date.new(1975, "August", 19)

Person = Struct.new(:familyName, :firstName, :income, :married)
tanaka_san = Person.new("田中", "一郎", 450, true)

Customer = Struct.new(:ID, :person, :birthday)
otokuisama = Customer.new(1202805, tanaka_san, tanaka_san_birthday)

otokuisama.person.familyName  # お得意様の姓を訊く
otokuisama.birthday.year            # お得意様の誕生年を訊く

レコード(Struct)の例(3)

my_customers = [
  Customer.new(1, Person.new("田中", "一郎", 450, true),
                  Date.new(1975, "August", 19)),
  Customer.new(2, Person.new("佐藤", "次郎", 400, true),
                  Date.new(1977, "May", 4)),
  Customer.new(3, Person.new("鈴木", "三郎", 500, false),
                  Date.new(1979, "November", 30)),
  Customer.new(4, Person.new("中村", "史朗", 600, true),
                  Date.new(1980, "January", 21)),
]

今日の課題