Why does the lack of an assignment operator allow me to change the Ruby constant without warning the compiler?

In the following two examples, I do the same by creating a String constant and using the concat method to change it. Since it is persistent, I expect a compiler warning, but I only get it in the second example when I use the assignment operator. Why is this?

X = "hello"
X.concat(" world")
puts X # no warning

X = "hello"
X = X.concat(" world")
puts X # warning: already initialized

Since the concat method modifies the string in place, this is usually what I will do, since there is no need to use an assistant operator. So, why does the presence of an assignment operator make the compiler identify these two operations as different?

+4
source share
4

, X. , " " . , X, .

+6

Ruby , , . X (X = "hello"), , , .

, - , , .

+7

"" , "":

X = "foo".freeze        # => "foo" 
X.concat("bar")

TypeError: can't modify frozen string
    from (irb):2:in `concat'
    from (irb):2

The Ruby Programming Languge.

+4

, X String. String, , . , , String, concat.

PickAxe .

0

All Articles