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
Tweet