自動化測試之路(三) ruby裏的get與set方法

照例可以先看端程序

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

 

發佈了43 篇原創文章 · 獲贊 10 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章