遊樂園

遊樂園

學習練習

簡介

實體變數

物件可以透過設定_實體變數_來保存自己的狀態。 這些變數存在於物件內部,通常用來儲存一些內部狀態。

實體變數一律以@開頭。 只要設定一個以@開頭的變數,就能建立新的實體變數。 例如:

class Repeater
  def hear(something)
    # Save what's been heard into a new instance variable called @heard
    @heard = something
  end

  def repeat
    # Return the value of the instance variable
    @heard
  end
end

repeater = Repeater.new
repeater.hear("Hello, friend!")
print repeater.repeat # Prints "Hello, friend!"

物件通常會在initialize方法中設定初始狀態,當你對類別呼叫new時,這個方法會自動被呼叫。

class Airplane
  def initialize
    @wings = 2
  end

  def wings
    @wings
  end
end

plane = Airplane.new
plane.wings # returns 2

initialize方法也可以接受引數,讓每個實體都能以自訂的狀態開始:

class Suitcase
  def initialize(locked)
    @locked = locked
  end
end

把_實體_變數視為對外部的讀取與寫入保持私有,是很好的做法。 我們改為定義方法來取得和設定它們的值。 例如:

class Suitcase
  def initialize
    @locked = false
  end

  def locked? # Query methods should be named with a trailing `?`
    @locked
  end

  def lock! # Methods which mutate state should have trailing `!`
    @locked = true
  end
end

suitcase = Suitcase.new
suitcase.locked? # false
suitcase.lock!
suitcase.locked? # true

Nil

Nil 是英文單字,意思是「沒有」或「零」。 在 Ruby 中,nil用來表示物件的_不存在_。 在其他程式語言中,null或none值可能扮演類似的角色。

# I do not have a favorite color
favorite_color = nil

Ruby 在第一次遇到實體變數時,會給它預設值nil,直到它被賦予其他值為止。

print @favourite_color # prints nil
@favourite_color = "blue"
print @favourite_color # prints "blue"

說明

你在遊樂園工作,收到了一份規格書,要設計一套管理入場與遊樂設施的系統。你的任務是為入場者(造訪樂園的人)建立模型。

1. 建立新的入場者

實作Attendee類別的Attendee#initialize方法,它應該接受一個身高(單位是公分),並將它存成實例變數。

Attendee.new(106)
# => #<Attendee:0x000055c33e6c7e18 @height=106>

2. 入場者有多高

實作Attendee類別的Attendee#height取值方法,它應該回傳該實例的高度。

Attendee.new(106).height
# => 106

3. 搭乘通行證的 id 是什麼

不是所有入場者都買了搭乘通行證,但我們需要知道他們有沒有通行證。為Attendee類別實作Attendee#pass_id取值方法,它應該回傳該實例的pass_id,如果入場者沒有通行證則回傳nil。

Attendee.new(106).pass_id
# => nil

4. 讓人們可以購買通行證

實作Attendee#issue_pass!來改變實例的狀態,並把通行證 id 的實例變數設為傳入的引數。它應該回傳通行證 id。

attendee = Attendee.new(106)
attendee.issue_pass!(42)
attendee.pass_id
# => 42

5. 撤銷通行證

有些遊客會做出不安全的行為而違反規定,所以樂園希望能撤銷通行證。實作Attendee#revoke_pass!來改變實例的狀態,並把通行證 id 設為nil。

attendee = Attendee.new(106)
attendee.issue_pass!(42)
attendee.revoke_pass!
attendee.pass_id
# => nil
透過 GitHub 編輯 連結會在新視窗或分頁中開啟
Ruby Exercism

準備好開始 遊樂園 了嗎?

註冊 Exercism,透過 21 個概念121 個練習 和真人引導來學習並精通 Ruby,全部免費。