Naked Splats Pass Blocks
Published .
Tags: ruby
Occasionally in Ruby I want to add some extra behavior to a method in a subclass, like creating an extra instance variable or triggering a callback. In cases like that, I generally want to receive the same arguments as in the superclass and pass them along through a call to super. Ruby makes that pretty easy; I can put a “naked splat” in the arguments list and super will automagically pass along those same arguments:
class B < A
def initialize(*)
super
do_an_extra_thing
end
end
However, I can never remember if (*) passes along a block argument. Well, it does! Here’s proof:
class A
def upcase_and_call_block(bar, &block)
puts bar.upcase
block.call
end
end
class B < A
def upcase_and_call_block(*)
super
puts "Done!"
end
end
B.new.upcase_and_call_block("test string") do
puts "Called the block!"
end
The output of this is:
TEST STRING
Called the block!
Done!
So, there ya go: the naked splat passes blocks.
I only need to know this once a year or so. I inevitably forget it, try to search for it, find nothing, and have to repeat the experiment above. Maybe I’ll find this article in the future!