Last active
October 17, 2018 09:35
-
-
Save dimameshcharakou/a846da7047e4b15cb05b39116af00e6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Enable frozen string literal: | |
# in one file with magick comment: frozen_string_literal: true | |
# enable globally: RUBYOPT="--enable-frozen-string-literal" | |
a = "a" | |
# copies everything about an object in Ruby except for its frozen state | |
b = a.dup | |
# copy everything about and object in Ruby | |
c = a.clone | |
a.frozen? # => true | |
b.frozen? # => false | |
c.frozen? # => true | |
abc = String.new | |
abc.frozen? # => false | |
d = "ü" | |
d.force_encoding('UTF-8') # will raise an exception | |
d.dup.force_encoding('UTF-8') # will not raise an exception | |
e = "aaa" | |
e.gsub!("a", "b") # => will raise an exception | |
e.dup.gsub!("a", "b") # => will not raise an exception | |
buffer = "" | |
buffer << "String A" # => will raise an exception | |
# Alternative approach | |
buffer += "String A" | |
buffer # => String A | |
# However, if you use += you’re creating a new string on every call, and thus | |
# losing the advantage of the memory benefits of a single string. It’s much | |
# better to instead create a mutable copy of the initial string via the dup | |
# method: | |
buffer = "".dup | |
buffer << "String B" | |
buffer # => String B | |
# Helpful sources: | |
# A command line interface for managing/formatting source file directive pragma comments (a.k.a. magic comments). | |
# https://github.com/bkuhlmann/pragmater | |
# Rubocop: | |
# https://rubocop.readthedocs.io/en/latest/cops_style/#stylefrozenstringliteralcomment |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment