Topic: Explain Syntax

Hello! Can someone please be kind of enough to explain what the following snippet of code actually does? I've been trying to figure it out for a while now...

self.old_rating.nil? ? nil : self.old_rating.rating

That's just some random code from the acts_as_rateable plugin, by the way. Thanks a lot!

Re: Explain Syntax

Sorry about the formatting, but the line has three parts:

self.old_rating.nil?     ? nil                 : self.old_rating.rating
condition                ? do this if true     : do this if false

Consider it a shortcut to avoid writing:
  if self.old_rating.nil?

The purpose of the line is to get the value of self.old_rating.rating only if it exists.

It's probably written that way because self.old_rating could potentially be nil. This way, you would avoid calling nil.rating and erroring out.

More info:

Last edited by vwoo (2007-06-30 22:27:17)

Vincent Woo Ruby on Rails Blog

Re: Explain Syntax

Ahh, thanks a lot! I thought it was that as I've used the syntax in PHP, but I was testing it wrong. Once again, thanks smile