Ruby if syntax (Two expressions)
Let's say you're using if
Ruby syntax that looks something like this:
if foo == 3: puts "foo"
elsif foo == 5: puts "foobar"
else puts "bar"
end
Is there a way to do this so that Ruby does two things in an if statement, for example:
if foo == 3
puts "foo"
foo = 1
elsif foo = ...
How do I do this so that I can use two operators when using the first syntax?
if foo == 3: puts "foo"; puts "baz"
elsif foo == 5: puts "foobar"
else puts "bar"
end
However, I advise against this.
Ruby allows semicolons to separate statements on one line, so you can do:
if foo == 3: puts "foo"; puts "bar"
elsif foo == 5: puts "foobar"
else puts "bar"
end
To be neat, I would probably terminate both statements with ;
:
if foo == 3: puts "foo"; puts "bar";
elsif foo == 5: puts "foobar"
else puts "bar"
end
If you have a great reason, I wouldn't do it, because of its effect on readability. A normal block if
with multiple statements is much easier to read.
I find that case statements look much better than if statements:
case foo
when 3
puts "foo"
when 5
puts "foobar"
else
puts "bar"
end
And it allows multiple operators to be used for each condition.