Symbols!

Apr. 18th, 2009 11:32 am
elz: (farewell sunnydale)
[personal profile] elz posting in [community profile] rubyonrails
Symbols in Ruby are the things that start with colons: :name, :muffins, :buffy_the_vampire_slayer. They can be a little tough to wrap your brain around (they confused the heck out of me for a while), so I thought I'd do a rundown.



Symbols aren't variables

You can't give them values; :name = "Buffy" will just give you an error.

Symbols aren't strings

"buffy" is not the same as :buffy. You can't do the same things to a symbol that you can do to a string: you can't add them together or subtract things from them, you can't change their case, you can't find out how long they are or generally mess around with them. You can turn a symbol into a string (:buffy.to_s) and you can turn a string into a symbol ("buffy".to_sym), but a symbol on its own isn't very flexible.

Tip: :buffy.to_s gives you "buffy" and "buffy".to_sym gives you :buffy, but "Buffy the Vampire Slayer".to_sym gives you :"Buffy the Vampire Slayer" because of the spaces. It looks a little weird, but it works the same way any other symbol does.

What symbols are used for

The most common place you'll find a symbol is as the key in a hash:

{:name => "Buffy", :address => "Sunnydale, CA", :job => "Vampire Slayer"}

:name doesn't need to be a variable; it doesn't contain any information. And it doesn't need to be a string; you're not doing anything with it or to it except using it to find a value. A good rule of thumb might be that anywhere you need an identifier that doesn't need to hold any other information or be changed or analyzed or displayed, that's a job for a symbol.

Why bother using symbols when you could just use strings

Symbols use less memory, and so they make your program more efficient. How do they do that? Since symbols are immutable and inflexible and generally no fun at parties, Ruby says, well, one :name is the same as any other :name, so I'll just store one copy of it in memory and give you that same copy anywhere you use it. It doesn't matter if one hash has {:name => "Buffy"} and another has {:name => "Faith"}, because :name isn't a variable, and it isn't holding that information for you. It's just a label.

Strings, on the other hand, all get their own spaces in memory. "muffins" and "muffins" live in two different places in memory even though they look exactly the same. That way something like "muffins".upcase! only affects one set of muffins, and not all the muffins you've ever created.

If you don't have an account you can create one now.
No Subject Icon Selected
More info about formatting

July 2010

S M T W T F S
    123
4567 8910
11121314151617
18192021222324
25262728293031

Style Credit

Expand Cut Tags

No cut tags