The speed of light.
Avogadro’s number.
Planck’s constant.
The mass of an electron.
I thought that I understood constants. Unchanging. Immutable. Then Ruby went and fucked it up.
My understanding of constants in Ruby was that they are represented by a capitalized bareword (often all upper case) which, once defined, would cause Ruby to pitch a fit if you were to try to reassign its value. Makes sense, right? So when I saw this I was a bit confused:
1 2 3 4 5 6 7 8 9 10 |
|
Wait.. whaaaaaa????
1
|
|
Aren’t we changing what BRAND represents? Yes and no. We are NOT changing the object to which the bareword “BRANDS” points. We ARE changing the contents of that array, or what I formerly thought of as the value for “BRANDS”.
1 2 3 4 5 6 |
|
But, wait! There’s more!
So, while the value of PI might be the same in your home as it is in Intercourse, Pennsylvania, Fucking, Austria, and Wetwang, Yorkshire UK (all real places, btw), a constant may not be the same everywhere in your code. Let’s try this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
So now we have two “PIE"s? Hello Namespacing! How’re the wife and kids?!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
What happens if we get rid of the “PIE” inside the class?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
But if we reverse it…
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Sooooooo… now we can’t call “PIE” from outside of the class? It only works from within the class? I guess we could call it a ‘Class Constant’? Yeah, let’s call it a Class Constant because, well, that’s what it’s called.
Let’s summarize:
- Constants can only be set to point to an object once.
1 2 3 4 |
|
- The object to which a constant points CAN be changed.
1 2 3 |
|
- Constants have a scope / are namespaced.
1 2 3 4 5 6 7 8 |
|