Episode 21 - Symbols

So far we've learned about Ruby data types such as numbers, strings, arrays, and hashes. One other data type that is used often in ruby is a symbol, which are very similar to strings. To define a symbol, you use a colon as follows:

x = "hello" # this is a string
x = :hello # this is a symbol

Symbols are immutable, which means they can't be modified after they're created. In other words, you can't do things like add symbols together the way you could with strings. This means symbols have fewer methods compared to strings, which means they take up less computer memory.

Symbols are most commonly used as the keys for hashes. Instead of defining a hash like this:

person = {"name" => "Dana", "email" => "dana@email.com"}
puts person["name"] # the output is Dana

We can define a hash using symbols instead:

person = {:name => "Dana", :email => "dana@email.com"}
puts person[:name] # the output is Dana

In practice, it's not much different, but again the advantage in using symbols is the efficient use of memory.

Exercises:

  1. Convert all three lines of the following code to use symbols instead of strings for the hash keys.
    product = {"name" => "Jacket", "price" => 49.99, "color" => "red"}
    puts product["name"] # the output is Jacket
    puts product["price"] # the output is 49.99
  2. Symbols have fewer methods compared to strings. For example:
    puts "star" + "fish" # this works!
    puts :star + :fish # this crashes!
    Create another example where you can do something with strings that would crash with symbols.