博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
why we use Symbols in Hash
阅读量:6804 次
发布时间:2019-06-26

本文共 1386 字,大约阅读时间需要 4 分钟。

 

Rather than using Strings as the keys in a Hash, it’s better practice to use Symbols. 

Symbols are just like Strings except they’re faster and take up less memory. The reason Symbols are so efficient is that they are immutable; they cannot be changed, so Ruby doesn’t have to allocate as much memory. Strings on the other hand, can be changed, so Ruby allocates more memory to allow for that. If you want a more thorough explanation of why they are faster, check out this

 

Let’s try using them as keys in a Hash. Here’s a version of a Hash that uses Strings as keys:

kitten = {  "name" => "Blue Steele",  "breed" => "Scottish Fold",  "age" => "13 weeks"}

We can rewrite it using Symbols:

kitten = {  :name => "Blue Steele",  :breed => "Scottish Fold",  :age => "13 weeks"}

Aside from the slight performance boost, another good reason to use Symbols is that Ruby 1.9 introduced a “shortcut” syntax for declaring Hashes with Symbols as keys. We could rewrite the above Hash as:

kitten = {  name: "Blue Steele",  breed: "Scottish Fold",  age: "13 weeks"}

It saves us having to type those annoying hash rockets (=>), and it closely models the syntax of other languages like JavaScript.

To wrap up, it’s a good idea to use Symbols as keys in a Hash because they’re slightly faster than Strings, and Ruby provides us a nice shortcut syntax.

 

转载于:https://www.cnblogs.com/iwangzheng/p/5448738.html

你可能感兴趣的文章
nginx 500 error
查看>>
Cocos2d基础笔记
查看>>
iptables 防火墙基础知识
查看>>
mac下安装redis以及redis扩展-----xampp
查看>>
课后作业-阅读任务-阅读提问-1
查看>>
国产CPU走到十字路口:谁来取代英特尔芯片?
查看>>
Android控件----Menu和Toast
查看>>
GPRS模块AT呼叫控制命令
查看>>
浅谈Iterator iterable
查看>>
kvm_博文大纲
查看>>
SpringBoot RESTful 应用中的异常处理小结
查看>>
OA发展新10年 泛微率先打“落地”牌
查看>>
一定要睡个好觉——有一个重要的原因!
查看>>
我的友情链接
查看>>
md5加密
查看>>
Elastix2.3安装与配置
查看>>
数据的载体
查看>>
软件架构--分享软件架构图
查看>>
用电脑自带画图工具加字方法
查看>>
惠普服务器10年中的五大错五大幸
查看>>