Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

simon buysse
simon buysse
9,716 Points

Ruby colon, arrow, equal sign syntax

Hi there!

I'm having some trouble wrapping my mind around the use of colons in Ruby. Let's take the next line as an example

before_action :check_auth, only: => [:edit, :update, :delete]

So if I'm correctly, colons in front of a word are used to make symbols and refer to either keys in a hash or methods/actions

I have no idea why there is a colon after the 'only'

Also, when do you use the arrow symbols? =>

If anyone has a clear explanation for this, or could refer me to a decent source where I can read up on it I would be so grateful!

Simon

3 Answers

Raymond Sapida
Raymond Sapida
33,049 Points

Hi Simon!

You're right about how colons are used for symbols and methods. From my understanding, only: is another way of creating a hash object. I've seen that line written as:

before_action :check_auth, only: [:edit, :update, :delete]

or

before_action :check_auth, :only => [:edit, :update, :delete]

I like to think of it as a hash or block being passed into the before_action method. Also, this stack overflow link might explain it better than I could.

Good luck and I hope this was helpful!

Raymond

simon buysse
simon buysse
9,716 Points

Hey, thank you for that answer Raymond Sapida.

If I'm understanding this correctly, both ':only =>' and 'only:' are notations to assign something to the symbol :only

Ruby's syntax really is quite unique and does require some getting used to imo..

Raymond Sapida
Raymond Sapida
33,049 Points

Yeah, that's exactly right. I think the latter is to encourage symbols as keys in hashes, but either one is good in my opinion.

And I completely agree with that sentiment about Ruby's syntax. There are so many ways to do one thing that it can get really confusing. It might help to read a styles guide like this one if you want to standardize it That's what I tried when I first went through the Ruby courses.