1、类的实例变量以@开头,类变量以@@开头,都是封装在类内部,无法直接访问
class Test
def initialize(name)
@name = name
end
end
t = Test.new
t.name # => 无法直接访问
为了可以读取、修改@name,可以自己写方法
class Test
def initialize(name)
@name = name
end
def name
@name
end
def name=(name)
@name = name
end
end
t = Test.new("kaka")
puts t.name # => kaka
t.name = "lala"
puts t.name # => "lala"
上面的程序可以改成
class Test
attr_accessor :name
def initialize(name)
@name = name
end
end
t = Test.new("kaka")
puts t.name # => kaka
t.name = "lala"
puts t.name # => "lala"
2、和其它语言不同,ruby class中类层可以执行程序
class Test
puts "test"
def initialize(name)
@name = name
end
end
当你实例化这个类时,就会执行puts "test"