Ruby 字符串和符号的不变性(如果我们将它们存储在变量中会怎么样)

Ruby immutability of strings and symbols (What if we store them in variables)

字符串是原始类型;每当您调用该字符串时,它都会有一个新的对象 ID。符号是引用类型;每当你创建一个符号时,你就创建了一个指向该值的指针。

我将符号存储在变量中:

var1 = :foo
var1.object_id # => 2598748
:foo.object_id # => 2598748

var2 = :foo
var2.object_id # => 2598748

var2 = "hello"
var2.object_id # => 70131755422100

我怎么可能创建第二个变量 var2,并且它具有与 var1 相同的对象 ID?我创建了第二个元素。是不是说变量也是指针?

两个变量都指向符号:foo。符号 :foo 只存储一次,对吧?

创建了两个变量,所以它们应该在内存中,不能在同一个地方,因为它们的名称不同。 var1var2需要存储起来,方便以后调用。如果它们具有相同的对象 ID,我不知道如何调用它们。如果有人能帮助我理解这一点,我将不胜感激。

Ruby 变量是对对象的引用,所以当你将一个方法发送给一个变量时,它引用的对象就是它被计算的上下文。查看评分最高的答案中的第一张图片(在已接受的答案下方)可能更清楚 here.

因此,为了弄清楚发生了什么,让我们深入研究一下文档,看看您的代码片段发生了什么。

Ruby 的 Symbol class 文档: https://ruby-doc.org/core-2.5.0/Symbol.html

Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program's execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.

Ruby 的 Object#object_id 文档: https://ruby-doc.org/core-2.5.1/Object.html#method-i-object_id

Returns an integer identifier for obj.

The same number will be returned on all calls to object_id for a given object, and no two active objects will share an id.

所以这是一步一步发生的事情:

# We create two variables that refer to the same object, :foo
var1 = :foo
var2 = :foo

var1.object_id = 2598748
var2.object_id = 2598748
# Evaluated as:
# var1.object_id => :foo.object_id => 2598748
# var2.object_id => :foo.object_id => 2598748

正如上面第一个 link 中所讨论的,Ruby 是按值传递的,但每个值都是一个 Object,因此您的变量都计算为相同的值。由于由相同字符串组成的每个符号(在本例中为 "foo")指的是同一个对象,并且 Object#object_id 总是 returns 相同对象的相同 ID,因此您会得到相同的 ID .