Craig Walker
Craig Walker

Reputation: 51717

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

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
       ^

Upvotes: 23

Views: 10480

Answers (2)

Craig Walker
Craig Walker

Reputation: 51717

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

Upvotes: 19

ennuikiller
ennuikiller

Reputation: 46965

ruby 1.9 allows this:

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

Upvotes: 40

Related Questions