☰
×
Jonathan ThomBlogProjectsContact

When Does the Magic Comment Work, and When Does it Not?

1.26.2020


Adding # frozen_string_literal: true to a ruby file will prevent strings in that file from being modified and can improve performance. This Stack Overflow thread is as good of an introduction as any. But you can't just throw it in anywhere and expect it to work. There are rules, which are hard to discover, but they exist.

Putting the comment after some other code within the file, including within a class, will not freeze the strings:

class Foo
    # frozen_string_literal: true

    def run
        puts "foo" << "bar"
    end
end

Foo.new.run
# => foobar
puts "Hello World!"

# frozen_string_literal: true

class Foo
    def run
        puts "foo" << "bar"
    end
end

Foo.new.run
# => foobar

However, putting the comment after other comments will work:

# TODO: Implement "baz"
# frozen_string_literal: true

class Foo
    def run
        puts "foo" << "bar"
    end
end

Foo.new.run
# => can't modify frozen String (FrozenError)

Adding an extra hash (or any character) to the comment will not freeze the strings:

## frozen_string_literal: true

class Foo
    def run
        puts "foo" << "bar"
    end
end

Foo.new.run
# => foobar
# frozen_string_literal: true, also remember to get milk later

class Foo
    def run
        puts "foo" << "bar"
    end
end

Foo.new.run
# => foobar

But not using any spaces behaves properly:

#frozen_string_literal:true

class Foo
    def run
        puts "foo" << "bar"
    end
end

Foo.new.run
# => can't modify frozen String (FrozenError)

As does putting empty lines above the comment:




# frozen_string_literal: true

class Foo
    def run
        puts "foo" << "bar"
    end
end

Foo.new.run
# => can't modify frozen String (FrozenError)

There's likely a reason for all of this, both in a practical sense and a "it works this way because this is what the underlying source looks like," but it was fun to uncover the rules through trial and error. There are other magic comments, and they behave in a similar fashion, but frozen_string_literal is likely the most relevant for your day to day programming life.

Other Posts

The Best Projects Can Be Done in a Weekend

Everyone Has Something To Offer

Book Thoughts: Capital and Ideology

Naive Diffie-Hellman Implementation in Ruby

PGP/GPG

Lessons from Sandi Metz

Benchmarking Arrays Full of Nils

Go, and When It's Okay to Learn New Things

Favorite Talks from RailsConf

Grouping Records by Month with Ruby

Front End Refactor

Add Timestamps to Existing Tables in Rails

Let Your Projects Breathe

The Busy and (Somewhat) Fit Developer

TuxedoCSS and the Rails Asset Pipeline

Gem You Should Know About: auto_html

Querying for Today's Date with ActiveRecord

Getting the Action Mailer to Actually Mail (with Mailgun)

Advice for New Epicodus Students