I'm trying to understand the use of # frozen_string_literal: true
in RoR and I understand the freeze
method protects the frozen strings from modification up to some extend, but what's the point given that it's as easy to change the string as just reassigning the value? I would expect freeze to block reassignment too if the idea is protecting the variable from modification.
2.7.2 :001 > str = "string"
=> "string"
2.7.2 :002 > str.freeze
=> "string"
2.7.2 :003 > str.frozen?
=> true
2.7.2 :004 > str << "fails"
Traceback (most recent call last):
4: from /Users/dev/.rvm/rubies/ruby-2.7.2/bin/irb:23:in `<main>'
3: from /Users/dev/.rvm/rubies/ruby-2.7.2/bin/irb:23:in `load'
2: from /Users/dev/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/irb-1.2.6/exe/irb:11:in `<top (required)>'
1: from (irb):4
FrozenError (can't modify frozen String: "string")
2.7.2 :005 > str = "stringfails... but this is fine?!"
=> "stringfails... but this is fine?!"
2.7.2 :006 > str
=> "stringfails... but this is fine?!"
I feel like I'm getting confused between freezing the string versus freezing the variable, but a lot of resources mention constants and compare the behaviour to them, so I'm unsure if the idea is to freeze the string assigned to the variable or the variable itself.
Aucun commentaire:
Enregistrer un commentaire