Ruby shorthand conditional statements

January 12, 2009
A look at Ruby's offering to conditional statements.

When programming we should always be trying to refactor our code and follow the "three strikes and your out" rule. Basically what this means is if you repeat the same sequence of code three times or more then you should realy refactor this into a generic method which is reused throughout the application. This will reduce the amount of code needed and is good programming practice.

If\Else or case statements in ruby follow the general structure as per most programming languages like Java, C++, C# etc but sometimes they we feel they can look pretty ugly especially when they get really large and there is no real way to refactor them. What we can do is improve the flow and structure of the code and ruby provides various options. Using "unless" would enable us to fit a full condition on one line but its pretty limited with only one real output returned. We like the following below as it allows us to return 2 possible results based on a condition all in the one line of code:

   1  refactor < 3 ? puts("No need to reafctor YET") : puts( "You need to refactor this into a  method" )

How this structure works is described below and pretty easy to follow.

   1  < Test Condition > ?  if true do this : else do this

Its something really small and basic but something we liked when switching our preffered development platform to Ruby on Rails.

Bookmark and Share

Why Ruby on Rails ?

Ruby On Rails Logo
Find out how Ruby on Rails could save your company time & money!

Latest News

Amazon S3 in AWS Management Console Demo

June 10, 2010
Amazon announce that the AWS Management Console now provides a simple and intuitive web interface for managing your Amazon S3 resources.
Read more »

Open Source ?

open source technology
Find out why savantis use open source technology & how this can benefit you !

Latest Tweet