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?
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).
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