Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant Assignment Bug in Ruby?

Tags:

ruby

We caught some code in Ruby that seems odd, and I was wondering if someone could explain it:

$ 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 that? The constant was appended to at the same time the local variable was.

Known behavior? Expected?

like image 364
aronchick Avatar asked Jan 01 '26 09:01

aronchick


1 Answers

Known behaviour. Constants don't mean that you can't modify the object it refers to, merely that it'll give you a warning (and only a warning) if you assign it to a different object.

In short, ruby constants aren't.

Note: This behaviour is listed in an answer to "What are the Ruby Gotchas a newbie should be warned about?" It's a worthwhile read.

like image 91
Andrew Grimm Avatar answered Jan 05 '26 20:01

Andrew Grimm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!