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

问题描述

限时删除!!

过去几天我一直在研究如何理解 Ruby 中的符号.我在谷歌上阅读了所有关于 Ruby 符号的文章,大部分都是不好的解释所以我来到这里,我看到关于这个主题的一些问题存在,但是我不明白,抱歉.

I have been looking the past days how to understand Symbols in Ruby. I read every article on Google about Ruby symbols, most of them are bad explanations so I come here, and I see some questions about this topic exists, however I do not understand, sorry.

根据我所读到的内容,我了解到符号是不可变且唯一的,因此内存消耗和性能优于常规字符串.

From what I have read I understand that symbols are immutable and unique, so the memory consumption and performance is better than regular strings.

问题 #1
符号在生活中的目的是否与字符串相同?符号的目的是作为方便的常量而不携带值,就像后面的部分:它是实际值吗?

Question #1
Are symbols purpose in life to serve the same niche as strings? Is the purpose of symbols to function as convenient constants without carrying a value, like the part after : is it the actual value?

问题 2
我什么时候真正知道在哪里使用符号?

Question #2
When do I actually KNOW where to use symbols?

我会非常欣赏你自己对符号的解释,而不是链接到 Google 上的文章(我确保我已经阅读了它!).

I would highly apprciate your own explanations of symbols instead of linking to articles on Google (I ensure that I already read it!).

如果你能提供比我在这里已经问过的更多的关于符号的信息,我也会感谢你的时间,因为我根本不理解它们,甚至不理解存储在 :symbol_something 中的内容,它是参考还是什么?

I do also apprciate your time if you can provide more info about symbols than what I already asked about here, because I do not understand them at all, not even what is stored in :symbol_something, is it a reference or what?

非常感谢您的帮助!

推荐答案

ruby 中的符号是一种有效利用不可变字符串的方法.例如,假设您想使用字符串my_key"作为散列键.简单地使用字符串既浪费空间又浪费效率,因为每次指定哈希键my_key"时,您都会在不同的内存位置创建不同的字符串实例,即使字符串值内容相同!因此,如果您有 100 个 my_hash['my_key'] 实例,则您有 100 个字符串 'my_key' 实例.符号 :my_key 并非如此.无论您使用多少次,都只有一个 :my_key 实例!

symbols in ruby are a way to efficiently utilize immutable strings. For example, suppose you want to use the string "my_key" as a hash key. Simply using the string is a waste of both space and efficiency since each time you specify the hash key "my_key" you are creating a different string instance in a different memory location even though the string value contents are the same! So if you have 100 instances of my_hash['my_key'] you have 100 instance of the string 'my_key'. Not so with the symbol :my_key. There is only ever one instance of :my_key no matter how many times you utilize it!

您应该在通常使用不可变字符串作为标识符的地方使用符号.

You should use symbols where you would normally uses an immutable string as an identifier.

这篇关于无法掌握 Ruby 中的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 19:43