クラスの作り方
継承が必要な場合だけ、< でスーパークラスを指定します。
class Test
end
class Test2 < Integer
end
インスタンスの生成は new で行います。new メソッドはインスタンスの生成後、initialize を呼びます。
ruby ではインスタンスの初期化は initialize メソッドをオーバーライドして行います。
class Test
def initialize
end
end
Test.new
引数がない場合 () の省略が可能です。
-- 基本型 --
def execute
end
def execute(arg1, arg2)
end
戻り値は最後に評価された式の値となります。return で指定しても構いません。
-- 戻り値あり --
def count
1
end
def count
return 1
end
visibility には public,private,protected があります。Default では public になります。
-- visibility の指定 --
class Test
def testPublic
"public"
end
def testPrivate
"private"
end
private :testPrivate
def testProtected
"protected"
end
protected :testProtected
end
メソッド名(引数=初期値)で引数に初期値を与えることが可能になります。
-- 初期値の指定 --
class Test
def execute(code = 1)
if code == 1
"hoge"
else
"huga"
end
end
end
p Test.new.execute #=> "hoge"
p Test.new.execute(2) #=> "huga"
-- クラスメソッドの書き方 --
class Test
def Test.string
"Test"
end
end
p Test::string #=> "Test"
インスタンス変数は @変数名 で宣言します。宣言する場所はどこでも良いようです。
但し初期化されていない場合 nil を返します。一般的には initialize で初期化するようです。
class Test
def initialize(num1, num2)
@num1 = num1
@num2 = num2
end
def num1
@num1
end
def num2
@num2
end
def setNum3(num)
@num3 = num
end
def num3
@num3
end
end
test = Test.new(1, 10)
p test.num1 #=> 1
p test.num2 #=> 10
p test.num3 #=> nil
test.setNum3(100)
p test.num3 #=> 100
クラス変数は、@@変数名で宣言します。
class Test
@@hoge = 1
end
ruby では アクセサメソッドを簡単に作ることが可能です。
attr_reader |
呼び出しメソッドのみ |
attr_writer |
代入メソッドのみ |
attr_accessor |
両方 |
class Test
def initialize
@num1 = 0
@num2 = 0
@num3 = 0
end
attr_accessor :num1, :num2, :num3
end
test = Test.new
test.num1 = 1
test.num2 = 10
test.num3 = 100
p test.num1 #=> 1
p test.num2 #=> 10
p test.num3 #=> 100
|