Hacker News new | ask | show | jobs
by edlebert 3828 days ago
I couldn't find any actual examples on how to use the new frozen string literals. Lots of discussion in the link provided, but that's it.
1 comments

The NEWS file defines what the pragma actually is,[1], but you'd use it like so:

    # frozen_string_literal: true
    str = 'foo'
    str << 'bar'
This will now produce an error:

    # main.rb:3:in `<main>': can't modify frozen String (RuntimeError)
It's equivalent to Ruby 2.1's String#freeze:[2]

    str = 'foo'.freeze
    str << 'bar'

    # main.rb:2:in `<main>': can't modify frozen String (RuntimeError)
Except that it will affect all strings created after the pragma mark.

You can also trigger this behavior globally with the --enable=frozen-string-literal option.

[1]: https://github.com/ruby/ruby/blob/v2_3_0/NEWS#L17-L26

[2]: http://ruby-doc.org/core-2.2.3/Object.html#method-i-freeze