$30 off During Our Annual Pro Sale. View Details »

How to specify `frozen_string_literal: true`

How to specify `frozen_string_literal: true`

RubyKaigi 2017 の LT での発表資料です。

Kazuhiro NISHIYAMA

September 19, 2017
Tweet

More Decks by Kazuhiro NISHIYAMA

Other Decks in Technology

Transcript

  1. How to specify
    frozen_string_literal: true
    Kazuhiro NISHIYAMA
    RubyKaigi 2017 LT
    2017/09/19
    Powered by Rabbit 2.2.1

    View Slide

  2. self.introduce
    One of Ruby committers
    Twitter, GitHub: @znz
    1/12

    View Slide

  3. What’s frozen_string_literal
    magic comment
    Specify string literals are frozen or not per fle
    Frozen string literals are faster
    Generate less objects
    Reduce GC
    2/12

    View Slide

  4. Example
    After coding if exist
    example:
    # -*- coding: utf-8 -*-
    # frozen_string_literal: true
    p ''.frozen? #=> true
    3/12

    View Slide

  5. Past release
    Add frozen_string_literal: false for almost
    *.rb fles when Ruby 2.3.0
    For compatibility with --enable=frozen-string-
    literal command line option of ruby
    4/12

    View Slide

  6. Changes in this year
    Recent Ruby programs tend to specify true, but
    ruby standard libraries are false.
    So I changed to frozen_string_literal: true in
    some fles which assigned to no maintainer in doc/
    maintainers.rdoc.
    5/12

    View Slide

  7. Review points before change
    Almost RuntimeError: can't modify frozen String
    points are:
    String#<<
    bang methods (e.g. String#sub!)
    6/12

    View Slide

  8. Overlooked modifcation
    IO#read(length, out_buffer)
    this buffer is overlooked
    7/12

    View Slide

  9. Find modifed string literal
    --debug=frozen-string-literal command line
    option is very useful
    examples:
    ruby --debug=frozen-string-literal test.rb
    make test-all TESTS='-v base64' RUBYOPT=--debug=frozen-string-literal
    8/12

    View Slide

  10. Tests
    --debug=frozen-string-literal needs to run
    codes.
    So tests are very important.
    9/12

    View Slide

  11. No change if can’t
    If no tests, there is no need to forcibly change it.
    I think working codes are useful than broken
    faster codes.
    10/12

    View Slide

  12. mkmf.rb
    mkmf.rb has many tests
    But mkmf.rb is too complex to me in a short time
    So I remain false
    11/12

    View Slide

  13. Conclusion
    No tests may overlook modifcations
    Use frozen_string_literal: true if you can
    You can use frozen_string_literal: false in
    some cases for compatibility for --enable=frozen-
    string-literal
    12/12
    Powered by Rabbit 2.2.1

    View Slide