ruby里的实例变量用一个@符号做前缀。但是不能直接访问,例如:
class Person
def initialize(name , age)
@name = name
@age = age
end
end
def initialize(name , age)
@name = name
@age = age
end
end
p1=Person.new("Tom",23)
puts p1.name #这一行会报undefined method `name'的错误
下面的代码是ruby里一个标准的属性访问器,它类似于getter和setter。有一点特别,就是属性名+等于号 来定义一个setter。
class Person
def initialize(name , age)
@name = name
@age = age
end
def name
@name
end
def age
@age
end
def age = (value)
@age = value
end
end
def initialize(name , age)
@name = name
@age = age
end
def name
@name
end
def age
@age
end
def age = (value)
@age = value
end
end
p1=Person.new("Tom",23)
puts p1.name #Tom
p1.age = 25
puts p1.age #25
ruby还提供一种便捷的写法:
class Person
def initialize(name , age)
@name = name
@age = age
end
attr_reader : name , : age
attr_writer : age
end
def initialize(name , age)
@name = name
@age = age
end
attr_reader : name , : age
attr_writer : age
end