The Difference Between :symbol and symbol:

Chris Oliver

August 12, 2013

I was perusing Twitter today and came across a recent post by @rncrtr about the differences between Ruby 1.8 style and Ruby 1.9 style symbols. You can find his original post at his website here.

You may see :symbol and symbol: used interchangeably in rails 3 and later. This was one of the most confusing things to me when I first started developing with ruby and rails until someone on the #rubyonrails irc channel (an excellent resource, by the way) explained it to me.

The difference is that a symbol with the colon before it is just a symbol (a variable). You will need a “fat arrow” after it if you are assigning something to it, like this:

# does the equals make me look fat?
:class => "content"

A symbol with the colon after the name is actually the same thing as above, but includes the fat arrow in it, so you don’t have to write it. It is shorthand for the first method, written like this:

class: "content"

This can look a bit weird when you are assigning variables to a symbol, but it works just fine and is less code to write.

Rn Crtr
Rn Crtr is the author of devderp.com.

P.S. You might enjoy following me on Twitter.


Comments

Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

© 2024 GoRails, LLC. All rights reserved.