22

这个问题处理传递给 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
       ^
4

2 回答 2

38

ruby 1.9 允许这样做:

{|a,b=1| ... } 
于 2009-11-14T21:24:39.270 回答
19

穷人的默认块参数:

def call_it &block
  block.call
end

call_it do |*args|
  x = args[0] || "foo"
  p "Called the block with value #{x}"
end
于 2009-11-14T21:33:10.423 回答