Ruby if语法(两个表达式)

Ruby if语法(两个表达式),ruby,syntax,if-statement,Ruby,Syntax,If Statement,假设您正在使用Ruby的if语法,如下所示: if foo == 3: puts "foo" elsif foo == 5: puts "foobar" else puts "bar" end if foo == 3 puts "foo" foo = 1 elsif foo = ... 有没有办法让Ruby在if语句中执行两件事,比如: if foo == 3: puts "foo" elsif foo == 5: puts "foobar" else puts "bar"

假设您正在使用Ruby的
if
语法,如下所示:

if foo == 3: puts "foo"
elsif foo == 5: puts "foobar"
else puts "bar"
end
if foo == 3
    puts "foo"
    foo = 1
elsif foo = ...
有没有办法让Ruby在if语句中执行两件事,比如:

if foo == 3: puts "foo"
elsif foo == 5: puts "foobar"
else puts "bar"
end
if foo == 3
    puts "foo"
    foo = 1
elsif foo = ...
我怎样才能使用第一种语法把两条语句放进去呢

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

但是,我建议不要这样做。

Ruby允许分号在一行上分隔语句,因此您可以:

if foo == 3: puts "foo"; puts "bar"
elsif foo == 5: puts "foobar"
else puts "bar"
end
为了整洁起见,我可能会用
终止这两个语句

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

除非你有很好的理由,否则我不会这么做,因为这会影响可读性。包含多个语句的正常
if
块更容易阅读。

我认为case语句看起来比if语句好得多:

case foo
when 3
  puts "foo"
when 5
  puts "foobar"
else
  puts "bar"
end

并且允许每个条件多个语句。

你可以考虑一个<代码>案例>代码>语句,在这个特定的,ER,案例中。为什么这个问题被否决了??为什么它必须在一条线上?第二种语法读起来好多了,依我看。可能还值得注意的是,你可以使用
然后
而不是
来将条件与实际表达式分开。+1是关于除非有充分的理由,否则不应该以这种方式进行编码的建议。你为什么反对它……只是感兴趣而已?:~)将多个命令放在以分号分隔的一行上肯定会遇到难以发现的bug。在本例中,您不会忽略任何内容,但可以想象您将“foo”扩展为一条实际的消息,该消息跨越相当多的水平空间。那么您就有可能忽略
;还有别的东西一直往右边走。它无法通过此处的代码审查:)