一个行块和if条件

时间:2014-04-23 10:51:09

标签: ruby

我有:

foos.each do |foo|
  unless foo
    puts "Foo is missing"
    next
  end
  # rest of business logic goes here
end

我想更好地写下它的最后一部分,比如

{ puts "Foo is missing"; next } unless foo

不幸的是,这不起作用。有没有人知道用if条件内联编写两个(块)命令的方法?

5 个答案:

答案 0 :(得分:6)

只需使用括号:

(puts 'a'; puts 'b') if true
#=> a
#=> b

答案 1 :(得分:3)

您正在寻找的内容可以使用括号:

(puts "Foo is missing"; next) unless foo

但在这种特殊情况下,最好写一下:

next puts "Foo is missing" unless foo

答案 2 :(得分:1)

使用begin..end阻止:

begin puts "Foo is missing"; next end unless foo

答案 3 :(得分:1)

foos.each { |foo| foo or ( puts "Foo is missing"; next )
  # the rest of the business logic goes here
}

答案 4 :(得分:0)

您可以使用or语法

[1,2,3].each do |x|
  puts 'two' or next if x == 2
  puts x
end

#=> 1
#=> "two"
#=> 3