The Difference Between Ruby Symbols and Strings
robertsosinski.com
The Difference Between Ruby Symbols and Strings
1–7 of 7 posts
Re: The Difference Between Ruby Symbols and Strings
#2Likewise, I think there are a lot of subjects like this that the majority of web "hackers" just don't understand. Awesome post and if there are other Ruby ninjas out there, please copy this style, it's really helpful to the community at large.
I would write this to you, Robert, if you had a comment section, but you don't. So I'm just going to leave it here on HN.
Re: The Difference Between Ruby Symbols and Strings
#3The way I used to teach symbols, not in ruby, but in some "other object language" that had such animals is to have people play with their tools. In such other languages we had these visual tools to inspect and see references between objects. One of the first things you learn is to understand that objects just have "slots" which are referenced through variable names (or indexes) and those slots simply hold pointers to other objects.
Now, once you get that, you can visually explore what a symbol is. Its an "immutable" object sitting in a global table. When you inspect these symbol objects, you see they map to a unique integer value (hey cool, like constants in C!!). And so on goes your understanding...the "name" of a symbol is an array of characters. Open an inspector on the symbol #hello and the symbol #goodbye and you can discover visually that the character $e that each different symbol contains points to the same exact character object in the system. There is only one character $e in the entire VM!!
ok, I probably went too far. Anyway, the point is if you had the right tools to explore, people just need a push in the right direction and their understanding will deepen on its own. I wish ruby had such visual tools...
Re: The Difference Between Ruby Symbols and Strings
#4Re: The Difference Between Ruby Symbols and Strings
#5Re: The Difference Between Ruby Symbols and Strings
#6test_str1, test_str2 = "test", "test" str = Benchmark.measure do 10_000_000.times do test_str1 == test_str2 end end.total
testsym1, testsym2 = :test, :test sym = Benchmark.measure do 10_000_000.times do testsym1 == testsym2 end end.total
Of course you might not need to create two strings, and definitely not two symbols. Somebody want to run this? (I'm on a communal computer with no Ruby.)
Re: The Difference Between Ruby Symbols and Strings
#7Of course, this is a feature that provides some people with some speed-ups and some pseudo-safety. But it basically goes against the advantage of modern scripting languages - the ability to program in the large, to use "integer" rather the umteen varieties of bit chunks provided by c and such.
The article explains symbols fine but I want to get to the next, better scripting language where such things are discarded.