Posted in Ruby

Why use a Ruby symbol?

The Ruby Newbie Guide to Symbols is a decent introduction to symbols in Ruby, though it doesn’t get into how symbols actually are implemented within the system. In short, though:

  • The only reason that symbols could be found preferable over strings is because they save on data, this because every use of the same symbol refers to the same object. Even though the programmer refers to it with its name the system can find it by referring to its number, which results in a faster lookup.
    • Note however that Symbols of course will not have String methods, so are relatively deficient if what you really want is a string with all its inherent string functionality.
  • The things a programmer might find valuable about a using symbol is that it’s immutable (it can’t be changed on runtime) – which sometimes is exactly what you want. In this respect, they can be used as constants – perhaps if you really, really want a constant whose identifier doesn’t begin with a capital letter.
    • Arguments for taking such an approach? Because you benefit from abiding by variable-naming conventions (for example, Ruby doesn’t enforce the constancy of constants, but variables that start with a capital letter in Ruby are automatically constants, and Ruby does automatically and helpfully warn you if you try to change these), and a constant with a non-uppercase first letter breaks conventions and thus could cause confusion to people reading your code. As such, a symbol – which is by its nature immutable – is a good choice both in terms of being functionally what you’re after (ie you can’t change its value) and for communicating to readers of your code that the variable in question, even with its non-uppercase first letter, really is a constant.

The Difference Between Ruby Symbols and Strings also emphasises the way that symbols are immutable, and the more predictable results + performance you therefore get when using them.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s