DEV Community

[Comment from a deleted post]
Collapse
 
philnash profile image
Phil Nash

One interesting caveat to this, is that you can make strings behave the same as a symbol in this case with a magic comment.

I just created a Ruby file that looks like this:

# frozen_string_literal: true

puts :rose.object_id
puts :rose.object_id

puts "rose".object_id
puts "rose".object_id

When this is run on the command line, the results are:

1009628
1009628
70288684550700
70288684550700

The comment frozen_string_literal: true means that whenever you use the string literal in this file, that is define a string using quote marks, that string is then immutable and a constant reference just like a symbol.

Strings created in other ways than the literal remain mutable and distinct objects though.

# frozen_string_literal: true

puts String.new("rose").object_id
puts String.new("rose").object_id

results in:

70158463624980
70158463624920