是否可以在Ruby中定义具有默认参数的块?

时间:2009-11-14 21:23:20

标签: ruby arguments default-value ruby-1.9

This question处理传递给Ruby块的可选参数。我想知道是否也可以使用默认值定义参数,以及它的语法是什么。

乍一看,似乎答案是“不”:

def call_it &block
  block.call
end

call_it do |x = "foo"|
  p "Called the block with value #{x}"
end

...导致:

my_test.rb:5: syntax error, unexpected '=', expecting '|'
    call_it do |x = "foo"|
                   ^
my_test.rb:6: syntax error, unexpected tSTRING_BEG, expecting kDO or '{' or '('
      p "Called the block with value #{x}"
         ^
my_test.rb:7: syntax error, unexpected kEND, expecting $end
    end
       ^

2 个答案:

答案 0 :(得分:31)

ruby​​ 1.9允许这样:

{|a,b=1| ... } 

答案 1 :(得分:17)

穷人的默认区块参数:

def call_it &block
  block.call
end

call_it do |*args|
  x = args[0] || "foo"
  p "Called the block with value #{x}"
end