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 ActiveRecord Basics AR Extensions Stateful Models

Why do you need a colon before the "if"?

In the video, the code requires a colon in front of the if statement for determining if the account entry has been approved. It is as follows:

after_save :update_account_balance!, :if => :approved?

That seems weird to me - why does this code not run without a colon in front of the "if"? Is there any explanation, besides that's just the appropriate syntax?

Thanks

2 Answers

Polly Sileo
Polly Sileo
3,696 Points

The : before the variable means it is a symbol. There is a good reference and explanation here: http://www.troubleshooters.com/codecorn/ruby/symbols.htm

As I've learned it symbols are used when you want a string to be immutable (unable to be changed). Strings can usually be changed (mutable) but if you want it to be forced to held as is then you can use a symbol. From reading this reference above, there are other reason and explanations but that's the one that so far has made the most sense to me.

Hope that helps.

Tom Sager
Tom Sager
18,987 Points

<p>You can blame this behavior on the comma in the line.</p>

<p>Without the comma, you could run</p>

after_save  :update_account_balance! if :approved?

<p>Ruby will parse the if statement, and only call after_save if the condition (approved?) returns true.</p>

<p>When you include the comma</p>

after_save :update_account_balance!, :if => :approved?

<p>the next element on the line is not a Ruby keyword. Instead, after_save is always called and the rest of the line is passed as an argument to after_save. In this case, the argument is a hash with a single element whose key is :if and whose value is :approved?. It is the activerecord callback that requires the key to be a symbol rather than a string. Note that although the key must be a symbol, the value can be a symbol, a string, an array or a Proc.</p>

<p>With either line of code the functionality is the same, but the way you get to the end result is different.</p>