Mark
Mark

Reputation:

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.

Upvotes: 9

Views: 14970

Answers (3)

Chuck
Chuck

Reputation: 237110

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.

For example, suppose

x = true

the following will evaluate true, and return y

x ? y :
=> y

likewise, this will evaluate false and return nothing

!x ? y :
=> 

add a term after the ':' for the else case

!x ? y : z
=> z

Upvotes: 18

Jared Knipp
Jared Knipp

Reputation: 5950

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.

Upvotes: 0

OregonGhost
OregonGhost

Reputation: 23769

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.

Upvotes: 4

Related Questions