views:

780

answers:

3

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.

+1  A: 

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.

OregonGhost
A: 

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.

aurealus
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"
Telemachus
+8  A: 

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.

Chuck
"since Ruby doesn't require parens like C" - I forgot that. Ok, makes sense why 'then' is needed. Didn't know about the semicolon - looks a little strange but it works. Very helpful. Thanks.
+1 for the semicolon tip.
Yaser Sulaiman