Reputation: 3155
Assume I have built an array of callable objects by doing
callables = []
callables << block1
callables << block2
callables << block3
callables << block4
Later I want to call these blocks. I understand I can do
callables.each { |block| block.call }
but I am wondering if I could make it even simpler by calling something like
callables.each :call
I have tried the code above but got ArgumentError. Does ruby support this kind of syntax?
Upvotes: 1
Views: 31
Reputation: 118271
You should try :
callables.each &:call
Array#each
don't accept any arguments. That's why, when you write callables.each :call
, :call
the symbol is passing to the method each
as an argument. But when you prefixed :call
with &
, each
knows that you are giving it a block as an argument, so it will work.
Upvotes: 3