Harry R. Schwartz

Code writer, sometime Internet enthusiast, attractive nuisance.

The author at the Palais du Luxembourg in Paris, November 2022. hacker news gitlab sourcehut pinboard librarything 1B41 8F2C 23DE DD9C 807E A74F 841B 3DAE 25AE 721B

Vancouver

British Columbia

Canada

vegan


Naked Splats Pass Blocks

hrs

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!


You might like these textually similar articles: