Skip to content

Instantly share code, notes, and snippets.

@mtanzi
Created January 21, 2019 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtanzi/3f5d280872406745c06a034a1dd4c643 to your computer and use it in GitHub Desktop.
Save mtanzi/3f5d280872406745c06a034a1dd4c643 to your computer and use it in GitHub Desktop.
Ruby literal Frozen

Frozen Literals 101

there a simple example to show how the literal can be handled in ruby

if we run the first file literal.rb the literal variable before call the .freeze method is not frozen

» ruby literal.rb
Before freeze: false
After freeze: true

We can set all the literal to be frozen passing the --enable=frozen-string-literal when we call the script

» ruby --enable=frozen-string-literal frozen.rb
Before freeze: true
After freeze: true

alternatevly we can add at the beginning of the file the # frozen_string_literal: true comment that set all the literal present in the file to be frozen

» ruby literal_frozen.rb
Before freeze: true
After freeze: true
a = "test"
puts a.frozen?
a.freeze
puts a.frozen?
# frozen_string_literal: true
a = "test"
puts "Before freeze: #{a.frozen?}"
a.freeze
puts "After freeze: #{a.frozen?}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment