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 20,000+ Swift developers and enthusiasts who get my weekly updates.