We can create, for example, new array following way:
values = Array.new(5) { rand(6) + 1 } # [3, 2, 3, 3, 2]
But how does it work in terms of function arguments?
For example if I define some function:
def some_func(a, b, c)
end
Function is defined with 3 arguments, I can make some of them optional but either way to call this function I would use
some_func(value1)
some_func(value1, value2)
some_func(value1, value2, value3)
But it doesn’t make sense to me in case of Array, where this block to define values go?
5 is definitely argument to a new function but what about block?
Thank you.
Passing a block to Array.new works the same way as passing a block to any other method: It’s a sort of implicit argument. It does not appear in the method’s argument list (unless you “reify” it into a Proc using
&), but you can call it usingyieldand check whether it is there usingblock_given?.For example if your
some_funcmethod were to take a block, it could look like this: