What's the difference between a string and a symbol in Ruby?

后端 未结 10 1325
说谎
说谎 2020-11-28 06:52

What\'s the difference between a string and a symbol in Ruby and when should I use one over the other?

10条回答
  •  忘掉有多难
    2020-11-28 07:17

    There are two main differences between String and Symbol in Ruby.

    1. String is mutable and Symbol is not:

      • Because the String is mutable, it can be change in somewhere and can lead to the result is not correct.
      • Symbol is immutable.
    2. String is an Object so it needs memory allocation

      puts "abc".object_id # 70322858612020
      puts "abc".object_id # 70322846847380
      puts "abc".object_id # 70322846815460
      

      In the other hand, Symbol will return the same object:

      puts :abc.object_id # 1147868
      puts :abc.object_id # 1147868
      puts :abc.object_id # 1147868
      

    So the String will take more time to use and to compare than Symbol.

    Read "The Difference Between Ruby Symbols and Strings" for more information.

提交回复
热议问题