Monday, July 02, 2007

Ruby attr_accessor使用


class Name
attr_accessor :name

def initialize
@name = ""
p @name.object_id
puts "\n"
end

def set_name(input_name)
name = input_name
self.name = input_name
end

def gets_name
p @name
p @name.object_id
p self.name
p self.name.object_id
end
end

a = Name.new
a.set_name('test')
a.gets_name
p a.name
p a.name.object_id

# >> 1647780
# >>
# >> "test"
# >> 1647790
# >> "test"
# >> 1647790
# >> "test"
# >> 1647790

puts "\n"
a.name = 'text'
a.gets_name
p a.name
p a.name.object_id

# >>
# >> "text"
# >> 1647680
# >> "text"
# >> 1647680
# >> "text"
# >> 1647680


self.name中的self是指当前的实例对象a,而self.name这个方法返回的则是对象a里的实例变量@name的值。
另:R4R第7章内容是关于ruby self的使用,说得非常详细,不同的作用域self代表的是不同的对象。
The default object (self) and scope In this chapter
■ The role of the current or default object, self
■ Scoping rules for variables and constants
■ Method access rules

No comments :