Today I Learned

hashrocket A Hashrocket project

The rest of keyword arguments 🍕

Sometimes you pass some extra keyword arguments to a method that doesn't handle them and you get the error ArgumentError: unknown keywords: ....

You can just use ** as the last argument to ignore the rest of the keyword arguments:

def make_pizza(cheese:, sauce:, **)
  puts "Making pizza with #{cheese} cheese and #{sauce} sauce"
end

make_pizza(cheese: 'muzzarella', sauce: 'tomato', chocolate: 'white', syrup: 'mapple')

=> Making pizza with muzzarella cheese and tomato sauce

You can also give it a name to group them:

def make_pizza(cheese:, sauce:, **rest)
  puts "Making pizza with #{cheese} cheese and #{sauce} sauce"
  rest.each {|k, v| puts "#{v.capitalize} #{k} is not good for you"}
end

make_pizza(cheese: 'muzzarella', sauce: 'tomato', chocolate: 'white', syrup: 'mapple')

=> Making pizza with muzzarella cheese and tomato sauce
=> White chocolate is not good for you
=> Mapple syrup is not good for you
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.