Project

General

Profile

Actions

Bug #15616

closed

Chained destructive methods fail when using +@ to unfreeze a frozen string

Added by cianooooo (Cian O) about 5 years ago. Updated about 5 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:91609]

Description

Using the +@ syntax to unfreeze a string does not work when chaining destructive methods

Consider the following;

foo = "bar".freeze
+foo.gsub!("bar", "car")

This raises;

FrozenError: can't modify frozen String

However, I would have expected this to work since +@ should return a duplicated mutable string.

Updated by ahorek (Pavel Rosický) about 5 years ago

+foo.gsub!("bar", "car")

stands for

+(foo.gsub!("bar", "car"))

and because foo is frozen, you'll get an error, see #15606

try this

foo = "bar".freeze
foo = (+foo).gsub!("bar", "car")

or

foo = "bar".freeze
foo = foo.gsub("bar", "car")

Updated by duerst (Martin Dürst) about 5 years ago

  • Status changed from Open to Rejected

Yes. It's a matter of precedence. The "Pickaxe" book describes it as

Single terms in an expression may be any of the following:

[some cases omitted]

  • Method invocation

That means that in +foo.gsub!("bar", "car"), the . of method invocation has higher precedence than the +, and so you need to use parentheses if you want to change the order of evaluation.

Actions

Also available in: Atom PDF

Like0
Like0Like0