Code & Clay – Notes to self. Mainly Ruby/Rails.

The naked asterisk

Andrew Berls writes about the naked asterisk in this post. I too stumbled across it whilst looking through Rails source.

Andrew says:

So what’s the deal with the unnamed asterisk? Well, this is still the same splat operator at work, the difference being that it does not name the argument array. This may not seem useful, but it actually comes into play when you’re not referring to the arguments inside the function, and instead calling super. To experiment, I put together this quick snippet:

class Bar
  def save(*args)
    puts "Args passed to superclass Bar#save: #{args.inspect}"
  end
end

class Foo < Bar
  def save(*)
    puts "Entered Foo#save"
    super
  end
end

Foo.new.save("one", "two")

which will print out the following:

Entered Foo#save
Args passed to superclass Bar#save: ["one", "two"]

The globbed arguments are automatically passed up to the superclass method. Some might be of the opinion that it’s better to be explicit and define methods with def method(*args), but in any case it’s a neat trick worth knowing!

If you really want to get to grips with Ruby development and gain a solid understanding of Object Oriented Design, I thoroughly recommend Sandi Metz's Practical Object Oriented Design in Ruby. It's the perfect introduction to OOP and pragmatic Ruby. You can buy it here.

“Meticulously pragmatic and exquisitely articulate, Practical Object Oriented Design in Ruby makes otherwise elusive knowledge available to an audience which desperately needs it. The prescriptions are appropriate both as rules for novices and as guidelines for experienced professionals.”

Katrina Owen, Creator, Exercism

Essential Reading: Learn Rails 6