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 ^
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.
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.
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 .
Python allows function arguments to have default values.
ruby 1.9 allows this:
{|a,b=1| ... }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With