ClassOne

Classの作成

必須単語

クラスを作るのに必須の単語は,

class, initialize, new, attr_accesor, attr_reader, インスタンス

である.

ObuNou.gif

次のMovieクラスをよく解読して,上の単語の使用法になじんでください. インスタンスというのは,newで作られたMovieクラスの子供で,ここでは, matrixやmjを指し,pp mjで中身を見ています.

Movie

まずMovieクラスを作る.下のところで,matrixとかをnewしてインスタンスを作っている. >|ruby| require 'pp'

class Movie

 REGULAR=0
 NEW_RELEASE=1
 CHILDRENS=2
 attr_reader :title
 attr_accessor :price_code
 def initialize(title, price_code)
   @title, @price_code = title, price_code
 end

end

matrix=Movie.new('Matrix', Movie::REGULAR) mj=Movie.new('MJ', Movie::NEW_RELEASE) totoro=Movie.new('Totoro', Movie::CHILDRENS) gundam=Movie.new('Gundam', Movie::CHILDRENS) pp mj p mj.title p totoro.price_code p totoro.price_code=Movie::REGULAR p mj.title="Michael Jackson"

<

いくつかの中身を見ています.ppはpよりも詳しくプログラムの 内容を表示するのに使います.

[bobsNewMacBook:Ruby/Refactoring/Refactv1] bob% ruby v0.rb
#<Movie:0x193660 @price_code=1, @title="MJ">
"MJ"
2
0
v0.rb:23: undefined method `title=' for #<Movie:0x193660 @price_code=1, @title="MJ"> (NoMethodError)
Class.gif

Rental

次にRentalクラスを作成. >|ruby| class Rental

 attr_reader :movie, :days_rented
 def initialize(movie, days_rented)
   @movie, @days_rented = movie, days_rented
 end

end

<

Customer

Customerクラスもつくって,実行.”\n"は"\n"に注意. >|ruby|

class Customer

 attr_reader :name
 def initialize(name)
   @name=name
   @rentals = []
 end
 def add_rental(arg)
   @rentals << arg
 end
 def statement
   total_amount, frequent_renter_points = 0,0
   result="Rental Record for #{@name}\n"
   @rentals.each do |element|
     this_amount=0
     case element.movie.price_code
     when Movie::REGULAR
       this_amount +=2
       this_amount += (element.days_rented-2)*1.5 if element.days_rented > 2
     when Movie::NEW_RELEASE
       this_amount += element.days_rented*3
     when Movie::CHILDRENS
       this_amount +=1.5
       this_amount += (element.days_rented-3)*1.5 if element.days_rented > 3
     end

     frequent_renter_points +=1
     if element.movie.price_code==Movie::NEW_RELEASE && element.days_rented > 1
       frequent_renter_points +=1
     end
     result += "\t"+element.movie.title + "\t"+this_amount.to_s + "\n"
     total_amount+=this_amount
   end
   result += "Amount owed is #{total_amount}\n"
   result += "You earned #{frequent_renter_points} frequent renter points"
   result
 end

end

<

>|ruby|

me=Customer.new('Nishitani') me.add_rental(Rental.new(matrix,2)) me.add_rental(Rental.new(mj,4)) me.add_rental(Rental.new(totoro,6)) me.add_rental(Rental.new(gundam,3))

  1. pp me

print me.statement+ "\n"

<
Sequence.gif

出力(statement)結果は次のとおり.

[bob-no-MacBook-Pro:Ruby/Refactoring/Refactv1] bob% ruby v1.rb
#<Movie:0x191734 @price_code=1, @title="MJ">
Rental Record for Nishitani
	Matrix	2
	MJ	12
	Totoro	6.0
	Gundam	1.5
Amount owed is 21.5
You earned 5 frequent renter points
Last modified:2011/01/13 11:04:57
Keyword(s):
References:[RubyPrimary]