Billjk
Billjk

Reputation: 10686

Ruby if syntax (Two Expressions)

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?

Upvotes: 3

Views: 612

Answers (3)

Mark Thomas
Mark Thomas

Reputation: 37527

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.

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270767

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.

Upvotes: 5

Confusion
Confusion

Reputation: 16861

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

However, I advise against it.

Upvotes: 5

Related Questions