大寫開頭,使用new 關鍵字可以建立新的類
類屬性 用@開頭
color_string = String.new
color_string = "" #等同
color_array= Array.new
color_array = [] #等同
color_hash = Hash.new
color_hash = {} #等同
time = Time.new
puts time
class Person
def initialize(name)
@name=name
end
def say(word)
puts "#{word}, #{@name}"
end
end
p1 = Person.new("hikari")
p2 = Person.new("lisa")
p1.say("konichiha")
p2.say("yoroshiku")
靜態屬性及方法
class Person
@@name="hikari"
def self.say
puts @@name
end
end
Person.say
set get 約定
原始方法
class Person def initialize(name) @name = name @test = "hexo" end def test=(value) @test=value end def test @test end end p1 = Person.new("ku") p1.test=("omg") # 括號可以省略#p1.test="omg" p1.test
attr_accessor
class Person attr_accessor :test end
方法封裝
預設是public公開,可設定private 私有訪問、 protected受保護的訪問
class Person def public_method end private def private_method end protected def protected_method end end
類的繼承
class Pet
attr_accessor :name, :age
end
class Cat < Pet
end
class Dog < Pet
end
本作品採用《CC 協議》,轉載必須註明作者和本文連結