views:

293

answers:

2

This question deals with optional arguments passed to a Ruby block. I'm wondering if it's also possible to define arguments with default values, and what the syntax for that would be.

At first glance, it appears that the answer is "no":

def call_it &block
  block.call
end

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

...results in:

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
       ^
+6  A: 

ruby 1.9 allows this:

{|a,b=1| ... }
ennuikiller
...and I'm on 1.8.7, which explains why it's not working for me. :-\
Craig Walker
+8  A: 

Poor-man's default block arguments:

def call_it &block
  block.call
end

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