Permanent binding error in Ruby?

We caught some code in Ruby that seems weird, and I was wondering if anyone could explain this:

$ irb
irb(main):001:0> APPLE = 'aaa'
=> "aaa"
irb(main):002:0> banana = APPLE
=> "aaa"
irb(main):003:0> banana << 'bbb'
=> "aaabbb"
irb(main):004:0> banana
=> "aaabbb"
irb(main):005:0> APPLE
=> "aaabbb"

Catch it? A constant was added at the same time that there was a local variable.

Known behavior? Expected?

+2
source share
4 answers

Catch it? A constant was added at the same time that there was a local variable.

No, it was not added, and there was no local variable.

One object referenced by both a constant and a local variable is added, but neither the constant nor the local variable has been changed. You cannot change or change a variable or constant in Ruby (at least not as your question implies), the only thing you can change is objects.

, , .

- , . , , , . . , . . . , . , .

, : , , Python, Java, #, ++, C, Lisp, Smalltalk, JavaScript, PHP, Perl , , , final const , .

, , , .

Ruby freeze , . , , , , , , . , , , dup. , , , : dup , , . freeze , , :

ORIG = ['Hello']
CLONE = ORIG.dup.freeze
CLONE[0] << ', World!'
CLONE # => ['Hello, World!']

. - (, : , , ) (, : , , ).

, , . Ruby: , , . , , .

+4

. , , , ( ), .

, .

. : " Ruby Gotchas?" .

+5

, , :

>> APPLE = 'aaa'
=> "aaa"
>> banana = APPLE
=> "aaa"
>> APPLE.freeze
=> "aaa"
>> banana.frozen?
=> true
>> banana << 'bbb'
TypeError: can't modify frozen string
    from (irb):5:in `<<'
    from (irb):5
0

Ruby "". ; , , , , .

If you look at it this way, the behavior is obvious and necessary; Apple is a pointer to a string object, as well as a banana. Then you edit the object that the banana points to. Apple points to the same object, so the change is reflected there.

0
source

All Articles