【问题标题】:Is it possible to define a block with default arguments in Ruby?是否可以在 Ruby 中使用默认参数定义块?
【发布时间】:2010-12-16 16:17:39
【问题描述】:

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
       ^

【问题讨论】:

    标签: ruby arguments default-value ruby-1.9


    【解决方案1】:

    ruby 1.9 允许这样做:

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

    【讨论】:

    • ...我在 1.8.7,这解释了为什么它不适合我。 :-\
    【解决方案2】:

    穷人的默认方块参数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-01
      • 2020-03-11
      • 1970-01-01
      • 2010-09-13
      • 2022-11-10
      • 2019-05-16
      • 1970-01-01
      • 2011-06-09
      相关资源
      最近更新 更多