Why don't more projects use Ruby Symbols instead of Strings?

前端 未结 4 1473
南笙
南笙 2020-12-17 18:29

When I first started reading about and learning ruby, I read something about the power of ruby symbols over strings: symbols are stored in memory only once, while strings ar

4条回答
  •  盖世英雄少女心
    2020-12-17 18:58

    One reason for the usage of strings may be the usage of yaml to define the values.

    require 'yaml'
    data = YAML.load(<<-data
        one:
          title: one
          tag: 1
        two:
          title: two
          tag: 2
      data
      )  #-> {"one"=>{"title"=>"one", "tag"=>1}, "two"=>{"title"=>"two", "tag"=>2}}
    

    You may use yaml to define symbol-keys:

    require 'yaml'
    data = YAML.load(<<-data
        :one:
          :title: one
          :tag: 1
        :two:
          :title: two
          :tag: 2
      data
      ) #-> {:one=>{:title=>"one", :tag=>1}, :two=>{:title=>"two", :tag=>2}}
    

    But in the yaml-definition symbols look a bit strange, strings looks more natural.

    Another reason for strings as keys: Depending on the use case, it can be reasonable to sort by keys, but you can't sort symbols (at least not without a conversion to strings).

提交回复
热议问题