zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    分析Ajax并爬取微博列表
    链表01
    Install ping command from ubuntu docker
    In container,I can't use man
    centos install glances
    centos 服务器命令下安装GUI
    firefox浏览器配置
    xshell替代产品
    Linux下将一个文件压缩分包成多个小文件
    Linux生成大文件
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5448738.html
Copyright © 2011-2022 走看看