4 ms·
Those colons are symbols, and (as a non-rubyist), yes, I think they were a bad idea. Ruby symbols (and atoms in Lisp / Erlang / Elixir) are a performance hack,
by miki123211 1y ago
Those colons are symbols, and (as a non-rubyist), yes, I think they were a bad idea.
Ruby symbols (and atoms in Lisp / Erlang / Elixir) are a performance hack, they are basically "interned" strings. They're immutable and are mostly used for commonly-repeated values, e.g. names of keyword arguments, enum values etc. Unlike strings, they're supposed to be treated as a single, opaque value, with no other properties beyond the name they represent. Most languages don't give you APIs to uppercase or slice symbols, though you can usually convert to strings and back if you really need to.
The performance advantage of symbols/atoms is that they're represented as pointers or offsets into a global pool, which contains their names. This means repeated instances of the same symbol take up much less memory than they would as ordinary strings, as each instance is just a single pointer, and the actual name it represents is only stored once, in the global pool. Comparing symbols is also much faster than strings, as two symbols representing the same name will always have the same offset, turning an O(n) character-by-character comparison into a simple O(1) comparison of pointers.
It's really strange to me that so many high-level languages, which prize themselves on "developer happiness" and "mental compression" force you to think about strings in this way, out of all things.
I think there's something to be said for having a single character that can be used to represent identifiers as strings. Giving your internal string type an interned representation (with automatic interning of literals and a method to intern arbitrary strings) is also an interesting idea, though I know far too little about interpreter design to have an opinion on how much performance difference it would make. Conflating those two ideas together just seems like a really bad deal to me.
- endorphine 1y agoIt just occurred to me that Ruby's symbols are pretty much the same as Rust's string slices. No?
- deleted 1y ago[deleted]
- jbverschoor 1y agoNo. A symbol is basically a constant such as for example HTTP_NOT_FOUND. The difference is that you don’t assign it a number, which means less decisions during development. Another difference is that it will be printed as the string, so no to_string boilerplate. The other colon path: is used for named parameters/keyword args. It’s the same syntax as a hash/dict, but as a parameter it does not have a default value in this case. The old syntax, but still supported for hash/dict was “key => value” Rust’s string slices are the equivalent of Ruby’s slices of an array: myarr[5..18]
- mdemare 1y agoNo, symbols are immutable strings, strings are mutable strings. Having both mutable and immutable strings is pretty useful.