照例可以先看端程序
class Person
def initialize( name,age=18 )
@name = name
@age = age
@motherland = "China"
end
def talk
puts "my name is "+@name+", age is "[email protected]_s
if @motherland == "China"
puts "I/'m Chinese."
else
puts "I/'m foreigner."
end
end
attr_writer :motherland
end
p1=Person.new("kaichuan",20)
p1.talk
p2=Person.new("Ben")
p2.motherland="ABC"
p2.talk
程序運行結果
my name is kaichuan, age is 20
I'm Chinese.
my name is Ben, age is 18
I'm foreigner.
>Exit code: 0
有過面向對象編程語言經歷的童鞋很容易可以看明白,但是裏面值的一提的是這句:“attr_writer :motherland”
這句話相當於我們面向對象編程語言的set方法,也可以這樣寫
def motherland=(value)
return @motherland =value
end
那麼相應的get方法爲 attr_ reader :motherland
相當於
def motherland
return @motherland
end
相應的 attr_accessor :motherland 相當於attr_reader:motherland; attr_writer :motherland