Great Ruby Shorthands For If…Then…Else

24 Dec

Ruby has some amazing shorthands for If…Then…Else Statements. These shorthands beautifully consolidate three or more lines of code into one readable line of code. I’m getting into the habit of using these a lot more consistently, so I wanted to share.

If…Then

Traditional

if today == ChristmasEve
  puts 'Santa's On His Way!'
end

Shorthand

puts 'Santa's On His Way!' if today == ChristmasEve

If…Else

Traditional

if today == ChristmasEve
  puts 'Santa's On His Way!'
else
  puts 'Snow'
end

Shorthand

today == ChristmasEve ? (puts 'Santa's On His Way!') : (puts 'Snow')

Do you use these Ruby shorthands?

Advertisements

2 Responses to “Great Ruby Shorthands For If…Then…Else”

  1. DM December 30, 2011 at 12:56 am #

    I don’t know if the first shorthand has an ‘official’ name, but the second one does:
    Ternary Operator.
    http://en.wikipedia.org/wiki/%3F: and http://en.wikipedia.org/wiki/Ternary_operation

    I wish the first shorthand (lets call it human readable if) was supported by C and Java. I used to use it a lot in Perl and I miss it. :/

    Something similar _is_ allowed but less human readable:

    EXPR || STATEMENT; // but STATEMENT can’t be of void return type.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s