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?
then
instead of :
to separate the condition from the actual expression - Andrew Marshall 2012-04-05 20:01
if foo == 3: puts "foo"; puts "baz"
elsif foo == 5: puts "foobar"
else puts "bar"
end
However, I advise against it.
; something_else
all the way to the right. It wouldn't get past a code review here : - Confusion 2012-04-05 20:00
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.
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.
case
statement instead, in this specific, er, case - Phrogz 2012-04-05 19:50