Great Ruby Shorthands For If…Then…Else

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?

Enjoy the article? Join over 17,500+ Swift developers and enthusiasts who get my weekly updates.

  • 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.

  • Gret! Thank’s for that! ๐Ÿ™‚

  • Jay

    Your quoting is off throughout the examples. Since you’re using a single quote for the apostrophe in “Santa’s”, your examples should probably be using double quotes.

  • Cheers for this! Has helped a lot condense my if statements on show pages in rails. Instead of

    else

    I can use

    @customer.warehouse.present? ? (link_to @customer.warehouse.name, warehouse_path(@customer.warehouse)) : (@customer.warehouse_id)

  • jonathanwy

    Or better, puts true ? “if true” : “if false”