如何理解Ruby中的符号 [英] How to understand symbols in Ruby

查看:30
本文介绍了如何理解Ruby中的符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管阅读了理解 Ruby 符号",在使用符号时,我仍然对内存中数据的表示感到困惑.如果一个符号,其中两个包含在不同的对象中,存在于同一个内存位置,那么它们如何包含不同值?我原以为相同的内存位置包含相同的值.

Despite reading "Understanding Ruby Symbols", I'm still confused by the representation of the data in memory when it comes to using symbols. If a symbol, two of them contained in different objects, exist in the same memory location, then how is it that they contain different values? I'd have expected the same memory location to contain the same value.

这是来自链接的引用:

与字符串不同,同名的符号在ruby会话期间被初始化并且只在内存中存在一次

Unlike strings, symbols of the same name are initialized and exist in memory only once during a session of ruby

我不明白它是如何区分同一内存位置中包含的值的.

I don't understand how it manages to differentiate the values contained in the same memory location.

考虑这个例子:

patient1 = { :ruby => "red" }
patient2 = { :ruby => "programming" }

patient1.each_key {|key| puts key.object_id.to_s}
3918094
patient2.each_key {|key| puts key.object_id.to_s}
3918094

patient1patient2 都是散列,没关系.:ruby 然而是一个符号.如果我们要输出以下内容:

patient1 and patient2 are both hashes, that's fine. :ruby however is a symbol. If we were to output the following:

patient1.each_key {|key| puts key.to_s}

那么会输出什么呢?红色",还是编程"?

Then what will be output? "red", or "programming"?

暂时忘记散列,我认为符号是指向值的指针.我的问题是:

Forgetting hashes for a second, I'm thinking a symbol is a pointer to a value. The questions I have are:

  • 我可以为符号赋值吗?
  • 符号只是一个指向变量的指针吗?
  • 如果符号是全局的,这是否意味着符号总是指向一件事?

推荐答案

考虑一下:

x = :sym
y = :sym
(x.__id__ == y.__id__ ) && ( :sym.__id__ == x.__id__) # => true

x = "string"
y = "string"
(x.__id__ == y.__id__ ) || ( "string".__id__ == x.__id__) # => false

因此,无论您创建什么符号对象,只要其内容相同,它都会引用内存中的相同对象.这不是问题,因为符号是一个不可变对象.字符串是可变的.

So, however you create a symbol object, as long as its contents are the same, it will refer to the same object in memory. This is not a problem because a symbol is an immutable object. Strings are mutable.

(回应下面的评论)

在原始文章中,值不是存储在符号中,而是存储在哈希中.考虑一下:

In the original article, the value is not being stored in a symbol, it is being stored in a hash. Consider this:

hash1 = { "string" => "value"}
hash2 = { "string" => "value"}

这会在内存中创建六个对象——四个字符串对象和两个散列对象.

This creates six objects in the memory -- four string objects and two hash objects.

hash1 = { :symbol => "value"}
hash2 = { :symbol => "value"}

这只会在内存中创建五个对象——一个符号、两个字符串和两个哈希对象.

This only creates five objects in memory -- one symbol, two strings and two hash objects.

这篇关于如何理解Ruby中的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆