[Ruby] 變數(Variable)與常數(Constant)

Wendy Wu
W-Learning Note
Published in
2 min readAug 21, 2019

變數

區域變數Local Variable

  • 以小寫字母或 _開頭
  • scope: class , module , def , do...end , {}
  • 沒有預設值

實例變數Instance Variable

  • @ 開頭
  • scope: 在相同的object中,所有methods都可以使用。
  • 預設值為 nil

類別變數Class Variable

  • @@ 開頭
  • scope: class和他的subclass, instance
  • 沒有預設值

全域變數Global Variable

  • $ 開頭
  • scope: 可在任何地方使用
  • 預設值為nil

虛擬變數Pseudo Variable

Ruby有一種稱為虛擬變數,是Ruby自定義的,看起來像local variable,但實際上你不能assign任何值給它,像是 self , nil , true , false 都是。

常數Constant

  • 以大寫字母(A-Z)開頭
  • scope: 在class或module中定義的常數,只能在該class或module中使用,在外面定義的則是global的。
  • 沒有initialize的常數會產生error
  • 所以的class和module都必須是常數
  • Ruby的常數是可以修改的,只是會跳出警告

--

--