Ruby 中的字符串和符号有什么区别? [英] What's the difference between a string and a symbol in Ruby?

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

问题描述

Ruby 中的字符串和符号有什么区别,什么时候应该使用一个?

What's the difference between a string and a symbol in Ruby and when should I use one over the other?

推荐答案

主要区别在于表示单个值的多个符号是相同的,而字符串则不然.例如:

The main difference is that multiple symbols representing a single value are identical whereas this is not true with strings. For example:

irb(main):007:0> :test.object_id
=> 83618
irb(main):008:0> :test.object_id
=> 83618
irb(main):009:0> :test.object_id
=> 83618

这是对符号 :test 的三个引用,它们都是同一个对象.

Those are three references to the symbol :test, which are all the same object.

irb(main):010:0> "test".object_id
=> -605770378
irb(main):011:0> "test".object_id
=> -605779298
irb(main):012:0> "test".object_id
=> -605784948

这是对字符串test"的三个引用,但都是不同的对象.

Those are three references to the string "test", but are all different objects.

这意味着使用符号可以潜在地节省大量内存,具体取决于应用程序.比较符号是否相等也更快,因为它们是同一个对象,比较相同的字符串要慢得多,因为需要比较字符串值而不仅仅是对象 ID.

This means that using symbols can potentially save a good bit of memory depending on the application. It is also faster to compare symbols for equality since they are the same object, comparing identical strings is much slower since the string values need to be compared instead of just the object ids.

至于何时使用哪个,我通常对几乎所有东西都使用字符串,除了像哈希键这样我真正想要唯一标识符而不是字符串的东西.

As far as when to use which, I usually use strings for almost everything except things like hash keys where I really want a unique identifier, not a string.

这篇关于Ruby 中的字符串和符号有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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