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?

3
  • 1
    You might consider a case statement instead, in this specific, er, case. Commented Apr 5, 2012 at 19:50
  • 1
    Why must it all be on one-line? The second syntax reads so much better, IMO. Commented Apr 5, 2012 at 19:57
  • 1
    It's also probably worth noting that you can use then instead of : to separate the condition from the actual expression. Commented Apr 5, 2012 at 20:01

3 Answers 3

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

However, I advise against it.

Sign up to request clarification or add additional context in comments.

2 Comments

Why do you advise against it...just interested? :~)
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 :)
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.

1 Comment

+1 For the advice on how one should never actually code this way unless there is a good reason.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.