2011年5月11日水曜日

Ruby言語 クラス定義

puts "##########クラスメソッドの定義########1"      

class Duration
    def display; puts self end    #インスタンスメソッド
end

duration = Duration.new    #インスタンスの生成
duration.display      #=>#<Duration:0x2855850>

puts "##########クラスメソッドの定義########2"

class Duration1
    def Duration1.print(x); p x end    #クラスメソッド
end

Duration1.print 2     #=>2


puts "##########クラスメソッドの定義########3"

class Duration3
    p self
   
    def self.print(x); #selfはクラス自身を指す
    p x
    p self
    end    #クラスメソッド
    def self.test(x ); p x += x end    #クラスメソッド
end

Duration3.print 2   #=>1
Duration3.test 2   #=>1
Duration3.test 2   #=>1

puts "リファクタリングとはプログラムの機能を変更しない修正の事"


puts "##########インスタンス化########4"

class Duration4
    def initialize(since,till)  #javaで言うコンストラクター的なもの
        @since = since
        @until = till
    end
    attr_accessor :since, :until    #指定したインスタンス変数に、seter/getterメソッドを組み込む
end

duration4 = Duration4.new(Time.now, Time.now + 3600)
p duration4.until
p duration4.since
p duration4.since = Time.now + 4600

puts "##########インスタンス化########5"

class Duration5
    def initialize (since,till)
        @since = since
       @till = till
 end

 def since=(value); @since = value end


 def till=(value);@till = value end

 def since
     return @since
 end

 def till
     return @till
 end

end


duration5 = Duration5.new(Time.now,Time.now + 3600)
p duration5.since
p duration5.till
p duration5.since = Time.now + 3600
p duration5.since


puts "##########クラス定義の追加########6"

class String
    def caesar; tr 'a-zA-Z', 'n-za-mN-ZA-M' end
end

puts "Learning Ruby".caesar

puts "##########クラス定義の追加########7"


class Fixnum
    alias original_addition + #元の定義を別のメソッドで退避、(別名で定義)
    def +(rhs) #再定義
        original_addition(rhs).succ #succは次の整数を返す
    end
end

p 1+ 1 #=>3
p 5 + 2  #=>8


puts "##########クラス定義の追加########8"

class Duration8
    def initialize (since,till)
        @since = since
       @till = till
 end
attr_accessor :since, :till  #アクセサメソッド
    def display(target=$>)
        super #Objyectクラスのdisplayをよびだす オーバーライドする
        target.write "(#{self.since}-#{self.till})" #displayの引数に渡す
    end
end


duration8 = Duration8.new(Time.now,Time.now + 3600)
duration8.display

puts "#########インスタンス変数########"

class Duration9
    def initialize (since,till)
        @since = since
       @till = till
 end
    def print_since;p @since end
end

duration9 = Duration9.new(Time.now-7,Time.now)
duration10 = Duration9.new(Time.now+7,Time.now + 14)
duration9.print_since
duration10.print_since


puts "#########クラス変数########"

class Foo
    @@class_variable = "foo"
    def ttt
        p @@class_variable
    end
end

class Bar < Foo
    p @@class_variable
    @@class_variable = "bar"
    def print
        p @@class_variable
    end
end

#foo = Foo.new
#foo.ttt
#bar = Bar.new
#bar.print

0 件のコメント:

コメントを投稿