繁体   English   中英

是否可以在Ruby中用默认参数定义一个块?

[英]Is it possible to define a block with default arguments in Ruby?

这个问题涉及传递给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
       ^

ruby 1.9允许这样做:

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

穷人的默认块参数:

def call_it &block
  block.call
end

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM