class Symbol

一个 Symbol 对象代表 Ruby 解释器内的命名标识符。

你可以显式地使用

在程序执行期间,对于给定的名称或字符串,将创建同一个 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 对象代表文本或数据。

这里有什么

首先,其他地方是什么。Class Symbol

这里,class Symbol 提供了对有用的方法,用于

查询方法

比较方法

转换方法