Ramziddin Makhmudov Ramziddin Makhmudov - 7 months ago 13
Ruby Question

Symbols (storing strings in variables vs symbols)

I saw that

object_id
of strings is always different whereas symbols'
object_id
is the same (if the value is equal). As I understand, the difference between symbols and strings is immutability and performance. Can't we just store a string inside a variable and freeze it?

( Sorry for stupid questions, I didn't find any answer to such question )

Answer

[...] can't we just store a string inside a variable and freeze it?

Almost, recent versions of Ruby can optimize frozen strings:

'foo'.freeze.object_id #=> 70313275108080
'foo'.freeze.object_id #=> 70313275108080

But this optimization is limited. It works for string literals (as shown above), but it doesn't work if the string is frozen later on:

a = 'foo'
a.freeze
a.object_id #=> 70313275335500

b = 'foo'
b.freeze
b.object_id #=> 70313275274260

Unless you enable the frozen_string_literal feature:

# frozen_string_literal: true

puts 'foo'.object_id
puts 'foo'.object_id

Output:

$ ruby test.rb
70185151269500
70185151269500

Or, from the command line:

$ ruby --enable-frozen-string-literal -e "puts 'foo'.object_id, 'foo'.object_id"
70102955495340
70102955495340