當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby Symbol類用法及代碼示例

本文簡要介紹ruby語言中 Symbol類 的用法。

Symbol 對象表示 Ruby 解釋器中的命名標識符。

您可以使用以下命令顯式創建 Symbol 對象:

在程序執行期間,將為給定名稱或字符串創建相同的 Symbol 對象,無論該名稱的上下文或含義如何。因此,如果Fred 在一個上下文中是一個常量,在另一個上下文中是一個方法,在第三個上下文中是一個類,那麽在所有三個上下文中, Symbol :Fred 將是同一個對象。

module One
  class Fred
  end
  $f1 = :Fred
end
module Two
  Fred = 1
  $f2 = :Fred
end
def Fred()
end
$f3 = :Fred
$f1.object_id   #=> 2514190
$f2.object_id   #=> 2514190
$f3.object_id   #=> 2514190

常量、方法和變量名稱作為符號返回:

module One
  Two = 2
  def three; 3 end
  @four = 4
  @@five = 5
  $six = 6
end
seven = 7

One.constants
# => [:Two]
One.instance_methods(true)
# => [:three]
One.instance_variables
# => [:@four]
One.class_variables
# => [:@@five]
global_variables.grep(/six/)
# => [:$six]
local_variables
# => [:seven]

Symbol 對象與 String 對象的不同之處在於 Symbol 對象表示標識符,而 String 對象表示文本或數據。

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Symbol類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。