Ruby if syntax (Two Expressions)

Go To StackoverFlow.com

3

Lets say you are using the if syntax for Ruby that goes like this:

if foo == 3: puts "foo"
elsif foo == 5: puts "foobar"
else puts "bar"
end

Is there a way to do it so Ruby executes two things in the if statement, say, like this:

if foo == 3
    puts "foo"
    foo = 1
elsif foo = ...

How can I make it so I can put two statements in using the first syntax?

2012-04-05 19:47
by Billjk
You might consider a case statement instead, in this specific, er, case - Phrogz 2012-04-05 19:50
Why was this question downvoted?? - Billjk 2012-04-05 19:52
Why must it all be on one-line? The second syntax reads so much better, IMO - Andrew Marshall 2012-04-05 19:57
It's also probably worth noting that you can use then instead of : to separate the condition from the actual expression - Andrew Marshall 2012-04-05 20:01


5

if foo == 3: puts "foo"; puts "baz"
elsif foo == 5: puts "foobar"
else puts "bar"
end

However, I advise against it.

2012-04-05 19:49
by Confusion
Why do you advise against it...just interested? :~ - Billjk 2012-04-05 19:53
Putting multiple commands on a single line seperated by semicolons is a surefire way to run into hard to find bugs. In this example you won't overlook anything, but imagine you expand "foo" into an actual message that spans quite some horizontal space. Then you run the risk of overlooking the ; something_else all the way to the right. It wouldn't get past a code review here : - Confusion 2012-04-05 20:00


5

Ruby permits semicolons to separate statements on a single line, so you can do:

if foo == 3: puts "foo"; puts "bar"
elsif foo == 5: puts "foobar"
else puts "bar"
end

To be tidy, I would probably terminate both statements with ;:

if foo == 3: puts "foo"; puts "bar";
elsif foo == 5: puts "foobar"
else puts "bar"
end

Unless you have an excellent reason though, I wouldn't do this, due to its effect on readability. A normal if block with multiple statements is much easier to read.

2012-04-05 19:50
by Michael Berkowski
+1 For the advice on how one should never actually code this way unless there is a good reason - Charles Caldwell 2012-04-05 19:53


2

I think case statements look far better than the if statements:

case foo
when 3
  puts "foo"
when 5
  puts "foobar"
else
  puts "bar"
end

And this allows for multiple statements per condition.

2012-04-06 02:25
by Mark Thomas
Ads