Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are block variables optional?

Non-block variables are obligatory:

def foo arg; end
foo # => ArgumentError

In order to allow optional arguments, a default value has to be supplied:

def foo arg = nil; end
foo # => nil

But block variables are optional:

def foo █ end
foo # => nil

Without a default value, an absent block variable is assigned nil, and in fact, block variables cannot take default values:

def foo &block = ->{puts :foo}; end
# => syntax error

On the contrary, a method can take an extra block that is not required in the definition:

def foo; end
foo{puts :foo} # => nil

What is the advantage of block variables being designed like this as opposed to non-block variables?

like image 210
sawa Avatar asked Aug 01 '13 06:08

sawa


1 Answers

There wouldn't be much point throwing an error when no block is given, since any method that uses either yield or block.call will throw an error anyway if there is no block. There also wouldn't be much point supplying a default block, since the default code to be executed can just be written into the method itself (which would be a lot neater than writing it inline with the arguments).

like image 143
Doydle Avatar answered Sep 16 '22 23:09

Doydle