why we use Symbols in Hash

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 blog post.


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.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值