Natasha The Robot

Currently learning... iPhone development!                                     You can follow me on Twitter here

Great Ruby Shorthands For If…Then…Else

Posted on

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?

  • DM

    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.

    • http://learning2program.wordpress.com Natasha Murashev

      Thanks for putting a name to the method :)