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?
+3
source to share
3 answers
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.
+5
source to share