Wednesday, April 13, 2011

How to write 'if' without using 'then' or 'end' in Ruby

I've found three ways to write the same condition in Ruby:

#1
if 1==1 
  puts "true" 
end

#2
puts "true" if 1==1

#3
if 1==1  then puts "true" end

Why can't I do this?

#4
if 1==1 puts "true"

I don't understand:

(1) Why then and end are needed in #3, and,

(2) Why I need to change the order to get #2 to work.

Statement #4 seems like the most natural way to write this. I don't understand why it's not possible.

From stackoverflow
  • The thing is that both ways actually are a natural way to think:

    if this is true then do something

    do something if this is true

    See? Ruby tries to get close to English syntax this way. The end is just necessary to end the block, while in the second version, the block is already closed with the if.

    To actually answer your question, I think there is no chance to get the then and end removed. Remember Pascal / Delphi? You have a then there as well. It's typical only for C-style languages to not have it.

  • What about using a colon instead of then like this? http://www.java2s.com/Code/Ruby/Statement/layoutanifstatementisbyreplacingthethenwithacolon.htm

    There are various ways you could short circuit if you wanted to do so.

    The conditional statement is just part of the Ruby syntax to make it more English like.

    Telemachus : For what it's worth, this use of the colon is gone as of Ruby 1.9 - same for the when tests in case statements. See David Black's "Son of 10 things to be aware of in Ruby 1.9"
  • The "if x then y end" syntax is meant for multiline conditionals while the "y if x" form is meant for concise single-line conditional statements. The then is necessary in the first case to tell Ruby that the condition is over (since Ruby doesn't require parens like C), and the end is necessary to tell Ruby that the whole if block is over (since it can be multiple lines).

    You can replace the then with a semicolon, because an end-of-line also signals the end of the condition. You can't get rid of the end with a multiline if. Either use the second form or the ternary operator if you want a concise one-liner.

    Yaser Sulaiman : +1 for the semicolon tip.

0 comments:

Post a Comment