2009-11-14 54 views
17

This question處理傳遞給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 
    ^

回答

28

紅寶石1.9允許這樣的:

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

...我在1.8.7,這解釋了爲什麼它不適合我。 : - \ – 2009-11-14 21:29:31

17

窮人的默認塊參數:

def call_it &block 
    block.call 
end 

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