Why we use the Symbols in Hash

Source: Internet
Author: User

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

Symbols is just like Strings except they ' re faster and take to less memory. The reason Symbols is, efficient is, and the They is immutable; They cannot is changed, so Ruby doesn ' t has to allocate as much memory. Strings on the other hand, can is changed, so Ruby allocates more memory to allow for that. If you want a further thorough explanation of why they is faster, check out the 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 " " weeks " }

We can rewrite it using Symbols:

Kitten = {  "Blue Steele",  "Scottish Fold " ,   " weeks " }

Aside from the slight performance boost, another good reason to use Symbols are that Ruby 1.9 introduced a "shortcut" Synta X for declaring hashes with Symbols as keys. We could rewrite the above Hash as:

Kitten = {  "Blue Steele",  "Scottish Fold " ,   " weeks " }

It saves us have 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 provi Des us a nice shortcut syntax.

Why we use the Symbols in Hash

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.