Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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        ^ 
like image 234
Craig Walker Avatar asked Nov 14 '09 21:11

Craig Walker


People also ask

How do I set default arguments in Ruby?

The syntax for declaring parameters with default values In order to define a default value for a parameter, we use the equal sign (=) and specify a value to which a local variable inside the method should reference.

How do you define a block in Ruby?

Ruby blocks are anonymous functions that can be passed into methods. Blocks are enclosed in a do-end statement or curly braces {}. do-end is usually used for blocks that span through multiple lines while {} is used for single line blocks. Blocks can have arguments which should be defined between two pipe | characters.

How do you define a method that can accept a block as an argument Ruby?

We can explicitly accept a block in a method by adding it as an argument using an ampersand parameter (usually called &block ). Since the block is now explicit, we can use the #call method directly on the resulting object instead of relying on yield .

Can we give default value to arguments?

Python allows function arguments to have default values.


2 Answers

ruby 1.9 allows this:

{|a,b=1| ... }  
like image 98
ennuikiller Avatar answered Sep 30 '22 19:09

ennuikiller


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 
like image 45
Craig Walker Avatar answered Sep 30 '22 20:09

Craig Walker