DEV Community

Discussion on: Yet Another Post About Ruby Blocks

Collapse
 
pinotattari profile image
Riccardo Bernardini

Another curiosity is around the number of parameters passed to yield, which in turn are sent as block parameters to your block. Are they enforced/requested by Ruby or not? Give it a try using irb - you'll be surprised with the result!

Interesting, I never tried before (although I used Ruby fairly a lot). This also is interesting

a = [1, 2, 3]
a.each {|*x| p x}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yagosansz profile image
Yago Santos • Edited

Hi Riccardo,

Thanks for sharing! I couldn't understand how it works though. Would you mind explaining what is happening behind the scenes? =)

I thought the * (splat operator) was only used to "spread" elements of a collection when passing it as an argument to a function.

Collapse
 
pinotattari profile image
Riccardo Bernardini

It works also the other way around, as the varargin in Matlab. For example, suppose I define

def foo(a, b, *c)
   p c;
end
Enter fullscreen mode Exit fullscreen mode

Here foo is a function that expects a number of arguments larger or equal than two. The first two arguments are assigned to a and b and all the remaining arguments (zero or more) are collected in an Array assigned to c. For example, if I call

foo(42, 33, 'x', nil 12)
Enter fullscreen mode Exit fullscreen mode

the function prints ["x", nil, 12], if I call

foo(42, 33)
Enter fullscreen mode Exit fullscreen mode

the function prints [ ], if I call

foo(42)
Enter fullscreen mode Exit fullscreen mode

I get an error

Thread Thread
 
yagosansz profile image
Yago Santos

Hi Riccardo,

Thank you for taking to explain it - it is more clear to me now how it works!