Today I Learned

hashrocket A Hashrocket project

Ruby String Mutability

Until Ruby 3 we need to explicitly call the method freeze on literal strings, so they become immutable. And, if you have a lot of literal strings in a file, this will be very repetitive and verbose. In order to let our code cleaner there is a magic comment that can be added in the top of each file.

the magic:

# frozen_string_literal: true

And it is done, all literal string are frozen now :)

example:

class Unfrozen
  def foo
    'bar'
  end
end
class StringFrozen
  def foo
    'bar'.freeze
  end
end
# frozen_string_literal: true
class ClassFrozen
  def foo
    'bar'
  end
end

To test that:

require 'spec_helper'

describe 'Ruby String Mutability' do
  it 'validates string mutability' do
    expect(Unfrozen.new.foo.frozen?). to be false
    expect(StringFrozen.new.foo.frozen?). to be true
    expect(ClassFrozen.new.foo.frozen?). to be true
  end
end
Randomized with seed 51265
.

Finished in 0.00179 seconds (files took 0.45396 seconds to load)
1 example, 0 failures

\o/

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.