Ruby Missing Keyword Argument: Find and Fix the Missing Name

Trace missing Ruby keywords through method definitions, hashes and wrappers. Tested examples distinguish an absent keyword from a supplied nil value.

Written by Technically reviewed by Jim Freeze · Reviewed

A Ruby missing keyword argument error means a method wants a named argument that the call did not give. Compare the missing name in the error to the method definition. Pass it explicitly as a keyword, or fix the hash or wrapper providing it. The exception is ArgumentError. A required keyword supplied with nil is present, though its value may be invalid for your application.

Go back to the first applicable application frame in the backtrace. See which receiving method you use, the actual argument keys you are sending, and any code forwarding between them. While you could add a default for a required key, this should only happen when omission of the key has some meaning. Otherwise, a default will cover up where the problem really was — missing input.

Ruby missing keyword argument comparison showing an absent name, a supplied nil value and a valid supplied name
A required keyword verifies that a name was sent. Check its value separately, and add a default only when omission is intended.

Read a Ruby missing keyword argument error

In Ruby, how you declare a method parameter makes a difference. When you follow a name with a colon and do not include a default value, you are declaring a required keyword. The caller must send the name. An identically-named local variable does not inherently meet the requirements, nor does sending an unrelated positional value. Take a look at the call syntax as well as the data being passed.

def greet(name:)
  "Hello, #{name}"
end

begin
  greet
rescue ArgumentError => error
  puts error.message.lines.first.strip
end
puts greet(name: "Mina")
# missing keyword: :name
# Hello, Mina

In this case, the method will not begin its normal processing until the caller supplies the required keyword. Before you make any changes, take a look at the exception’s name and first message line. If the message says that the keyword was unknown, the caller sent a name that the signature does not allow. If it says there is a positional count mismatch, first see which positional arguments the caller sent.

While debugging these cases separately, remember that a typo can cause a missing-name complaint because it prevented the intended name from reaching the method. However, adding all possible spellings to the method signature makes it harder to understand what your public API provides. Change the caller to use the agreed upon name, and save a regression test for that call.

Required, optional and present with nil

A required keyword answers “was the name supplied?”, not “is the value valid?”. It promises nothing about whether the supplied value is nonempty, a string or useful. This is why replacing a missing keyword with nil may prevent the original exception but cause another failure inside the method.

def required_value(name:)
  name
end

def optional_value(name: "Guest")
  name
end

p required_value(name: nil)
p optional_value
p optional_value(name: nil)
# nil
# "Guest"
# nil

The default for an optional keyword gets used when the caller omits the name. It does not get used when there is an explicitly-supplied nil value. So, determine for yourself if absence (not giving) and nil should be equivalent things in your application. If they represent something different, preserve that difference at the interface level instead of turning everything into a generic fallback.

Input situationRequired keywordKeyword with a default
Name omittedRaises a missing-keyword errorUses its default
Name supplied with nilAccepts the keyword’s presenceUses the supplied nil
Name supplied with a valueReceives that valueReceives that value

For example, creating a default customer identifier would mislead users. Creating a documented fallback for an optional display label might be reasonable. The syntax cannot decide this product decision for you. Decide what contract you want first, then use required keywords, defaults and explicit value verification to enforce it.

Inspect the receiving method’s parameters

Do not assume that the method open in your editor is the one getting called. A subclass can override it, a module can provide it, and a wrapper can forward calls to another object. Examine the bound method on the actual receiver. The parameter metadata on that bound method distinguishes between required keywords, optional keywords and a keyword-rest parameter.

class Delivery
  def label(name:, copies: 1, **extras)
    [name, copies, extras]
  end
end

p Delivery.new.method(:label).parameters
# [[:keyreq, :name], [:key, :copies], [:keyrest, :extras]]

The keyword-rest parameter gathers additional keywords but does not provide a missing required name. Adding it just to stifle complaints changes the accepted input. Use it if the method intentionally supports an open set of options, and retain explicit parameters for inputs with a defined purpose.

If method definitions and hashes are still foreign territory, the Ruby programming language overview takes those concepts through a complete program. For this error, focus on finding the receiving method’s exact signature and comparing it with the names supplied by the failing call.

Fix a Ruby missing keyword argument from a hash

first examine each of the hash keys. Strings are not symbols even when their displayed characters appear to be identical. Input parsed from an external source (parser, etc.) may deliver strings whereas a named Ruby keyword parameter expects its matching symbol name.

def address(city:, **extras)
  [city, extras]
end

payload = { "city" => "Leeds" }
begin
  address(**payload)
rescue ArgumentError => error
  puts error.message.lines.first.strip
end
p address(city: payload.fetch("city"))
# missing keyword: :city
# ["Leeds", {}]

Notice in this example how the keyword-rest parameter makes the distinction visible: although the rest parameter is able to accept additional keys, it is not able to satisfy the required “city” keyword. The corrected call explicitly maps the known input field and also utilizes a lookup that raises an exception if that field is missing so that an missing source field is not silently replaced with nil.

It is generally easier to map only selected fields as opposed to transforming all keys and forwarding the entire payload. Mapping selected fields provides documentation on which inputs this method will use. It gives you a place to validate values and reject unexpected input according to your application’s needs. Do not treat unrestricted keyword forwarding as a substitute for input validation.

Preserve keywords through wrappers

A direct call may work but fail under the same conditions using the same call through a wrapper. Examine what the wrapper received and what the wrapper sent. Only sending positional arguments can change the shape of a keyword call. For transparent delegates Ruby’s shorthand preserves both positional arguments and keywords and the block together.

def destination(city:)
  block_given? ? yield(city) : city
end

def relay(...)
  destination(...)
end

puts relay(city: "Leeds") { |city| city.upcase }
# LEEDS

The Ruby Style Guide’s argument-forwarding guidance recommends this shorthand for suitable delegates. However, forwarding the block is also a behavioral choice. Keep an explicit signature when a wrapper needs to filter, validate or transform inputs. Test the wrapper itself: a successful direct-call test does not establish proper forwarding.

When an upgrade reveals the error compare the installed dependency’s signature to the documentation for that version. Try not to simply copy a call from an older tutorial without checking assumptions. Even though a changed required keyword requires intentional caller update(s) you shouldn’t add a blanket rescue around every operation.

Try the missing-keyword exercise

Which call below fails: the one providing nil or the one providing no name? Make your prediction prior to opening up the answer. Since the method returns the input without validating it this isolates the issue at hand — keyword presence. We’re not determining whether nil would be appropriate in your real application here.

def recipient(name:)
  name
end

p recipient(name: nil)
begin
  recipient
rescue ArgumentError => error
  puts error.message.lines.first.strip
end
Reveal the output and the reason
nil
missing keyword: :name

The first call supplies the required name and returns nil. The second omits the name and raises before the body runs. If the application needs a nonempty string, add value validation separately. Adding a default changes the presence contract; it does not validate the value.

Test the Ruby missing keyword argument fix

Save original failing call inside of a regression test alongside a normal successful call. Test also missing input, supplying nil explicitly and types used by source payload’s keys. Each case tests different contracts. For wrappers run your test through the same entry point as used by the running application rather than testing just the destination.

If tests use substitutes, RSpec’s verifying instance doubles compare calls against the real method’s positional and keyword signature when that class is available. This is a documentation-based recommendation. These examples ran on official Ruby 4.0.0 WASI; native gems, a deployed application and an RSpec suite were not tested.

Keep exception handling narrow. After adding a guessed keyword, retrying an entire operation may repeat work done before a deeper call failed. Identify the failing definition, fix its caller and verify the expected value. Prefer a clear error near the input boundary over silently sending invented data further into the system.

Takeaway

To resolve a Ruby missing keyword argument error match the expected name provided in your error messages to your actual calling code. Consider whether string keys or symbol keys you use and whether defaults make sense in your codebase for required named arguments or forwarded through wrappers. Understand that present with nil is different than absent; fix where your caller lost track of providing the keyword, and ensure both correctness of presence and quality of value are verified independently during testing.