Ruby Unknown Keyword Argument: Find the Rejected Option

Find which Ruby method rejects an option, correct typos and route payload fields deliberately. Tested examples show why accepting extra keywords can hide a bug.

Written by Technically reviewed by Jim Freeze · Reviewed

When a Ruby program invokes a method with a named option that the method did not expect, a Ruby unknown keyword argument error occurs. Compare the name found in the error message with the method’s actual parameters. Fix a spelling error, omit an option that is not needed, or forward it to the method that owns that option. Never just add a catch-all keyword parameter to suppress the error.

While this is technically an ArgumentError, the message specifically points out a discrepancy: one of the keywords passed was not known to the receiving method. Although the value might be acceptable, the name is not acceptable to that method. Begin with the failing invocation and the first relevant application frame in the backtrace. Then look at the receiving method and its parameters.

Ruby unknown keyword argument decision guide for correcting, routing or deliberately accepting an extra option
Choose what the unexpected keyword needs: a corrected name, the right receiving method, or explicit support that implements its behavior.

Read a Ruby unknown keyword argument message

The label method below accepts a prefix. However, its caller also supplies a suffix. There is no suffix parameter in the definition, so Ruby rejects the call before running the normal method body. Changing the suffix value cannot repair that mismatch. First decide whether the caller should have sent this option at all.

def label(prefix: "Box")
  prefix
end

begin
  label(prefix: "Crate", suffix: "A")
rescue ArgumentError => error
  puts error.message.lines.first.strip
end
puts label(prefix: "Crate")
# unknown keyword: :suffix
# Crate

The call with a proper name succeeds because it only utilizes a valid keyword parameter. Nevertheless, leaving off an option is permissible only if you can establish that you were not intentionally providing that option or that it was superfluous. If you wish to incorporate a suffix in your application, determine which method will handle that function. Invoking a method that intentionally excludes a function you desire is not equivalent to fixing the issue.

Review the entire first line of the error message, including the name of the unknown keyword. If you get an error complaining about a missing-keyword, it indicates that the invoking application did not supply a name for each required keyword name. If you receive an error complaining about an unknown-keyword, it means that the invoking application supplied a name for a keyword that the invoked application did not accept. Positional-count errors indicate some other circumstance. These distinctions help ensure that you do not adjust default values or positional-argument counts when the issue is due to a name for a keyword.

Find the method Ruby actually called

You could be looking at a perfectly legitimate name of the method you were attempting to invoke but still be reviewing the wrong definition. A subclass could redefine it, a module could define it or a wrapper could invoke an entirely different object. Identify which method was invoked by determining the actual receiver. Determine where that method came from by identifying its owner. Determine which interface is expected by reviewing its parameters.

class Printer
  def print_label(prefix: "Box")
    prefix
  end
end

printer = Printer.new
bound = printer.method(:print_label)
p bound.owner
p bound.parameters
# Printer
# [[:key, :prefix]]

In this illustration, prefix has a default value and there are no keyword-rest parameters. As such, the permitted interface is easy to view. For methods defined in Ruby, identify the source location of the bound method to locate the definition. There is no Ruby source location for native methods. Instead, consult the versioned reference documentation for that version of the native method.

Next, check the documentation against the dependency version your application loads. An option available in a newer release may be absent from an older one. Equally, an update can remove an option. Identify the running implementation before choosing an upgrade as your repair. Copying an option from an unrelated method remains a mistake regardless of version.

Fix a Ruby unknown keyword argument from a typo

Spelling is part of a contract. Two names can resemble each other almost identically and still be different keywords. If the intended parameter has a default, a flexible method could treat the misspelled option as an additional option and proceed with that default. A rigid signature would reveal the error immediately, before the unexpected behavior becomes more difficult to justify.

def format_label(prefix: "Box")
  prefix
end

begin
  format_label(prefx: "Crate")
rescue ArgumentError => error
  puts error.message.lines.first.strip
end
puts format_label(prefix: "Crate")
# unknown keyword: :prefx
# Crate

Change the caller to use the spelling established by the receiving method. Avoid creating aliases for each typo: that turns accidental spellings into an interface you have to maintain. If compatibility truly requires two names, document both and test what happens when a caller supplies both together. The precedence rule should be a decision, not an accident.

Map incoming hashes to the intended interface

Incoming hashes often hold data for several operations. Expanding the whole hash into keyword arguments sends every field across this method boundary. Some fields may belong to transport metadata or logging instead. Build an intentional call using the fields this method owns. In the example below, the destination needs the city; tracking requires a separate decision.

def destination(city:)
  city
end

payload = { city: "Leeds", tracking: true }
begin
  destination(**payload)
rescue ArgumentError => error
  puts error.message.lines.first.strip
end
puts destination(city: payload.fetch(:city))
# unknown keyword: :tracking
# Leeds

An explicit mapping makes the inputs for your method visible at the site of invocation. However, it determines nothing regarding tracking. If tracking is required, forward it to the component responsible for that behavior. Suppressing a field is correct only when ignoring it is your intended policy and not simply because suppressing it eliminates an exception.

Alongside spelling, check key types. Strings and symbols are distinct keys even when their letters look identical in a printed hash. Normalization may be useful at an input boundary, but it does not fix an unsupported option name. A correctly typed key can still refer to an option the method does not accept.

For practice with small methods and collections, the Ruby code examples guide contains programs you can adapt. When reproducing this error, reduce the example below the size of your application. One receiving definition and the exact input hash usually make the mismatch easier to identify.

Choose whether extra keywords belong in the API

Keyword-rest parameters collect all remaining keywords into one hash. They are useful for APIs which pass through or otherwise process arbitrary numbers of options. Adding keyword-rest does not mean you are implementing those options. The method body still has to decide how to use each accepted option.

def flexible_label(prefix: "Box", **extras)
  [prefix, extras]
end

p flexible_label(prefx: "Crate")
# ["Box", {prefx: "Crate"}]

Here’s an example which accepts a typo but proceeds with its default prefix and produces no changes in the produced label. Thus, adding support for keyword-rest allows you to hide caller errors. Prior to accepting an unintended name, decide if it should cause an error, become documented extensions or go to a particular downstream API. Acceptance does not imply an implementation.

SituationUseful repairWhat to avoid
Misspelled supported optionCorrect the caller’s nameSilently retaining the default
Option belongs elsewhereRoute it to its ownerForwarding the whole payload blindly
Genuine new behaviorAdd and test explicit supportAccepting a value without using it

Check forwarding without widening the destination

A wrapper and its destination have separate signatures. Forwarding preserves the caller’s arguments; it does not make those arguments valid for the target. Therefore, a wrapper that forwards correctly can still receive an unknown-keyword error from the method it calls. Inspect both definitions before widening either signature, and locate the method that actually rejected the name.

The Ruby Style Guide’s argument-forwarding guidance recommends shorthand for suitable delegates. It also forwards the block, which matters when replacing an existing wrapper. Keep an explicit signature when options need filtering or transformation. Most importantly, test calls through the wrapper instead of assuming direct-call tests cover that path.

Try the unexpected-keyword exercise

Which call raises an exception, and which returns the default prefix? These methods differ in whether they accept extra keywords. Predict both outcomes before opening the answer. Both calls use the same misspelled name, so concentrate on what the permissive signature changes. Also ask whether either result matches the caller’s apparent intention to request a Crate label.

def strict(prefix: "Box")
  prefix
end

def permissive(prefix: "Box", **extras)
  prefix
end

begin
  strict(prefx: "Crate")
rescue ArgumentError => error
  puts error.message.lines.first.strip
end
puts permissive(prefx: "Crate")
Reveal the output and the hidden mistake
unknown keyword: :prefx
Box

The strict call rejects the typo. The permissive call collects the extra keyword, ignores it in the body and returns the default. Neither call produces the requested Crate label. Correcting the name restores the intended behavior; merely removing the exception does not. Keep the expected result in the regression test.

Verify the Ruby unknown keyword argument fix

Test the original failing call and the repaired call, including their results. Merely checking that an exception disappeared misses the bug demonstrated above. A useful regression test proves that the requested option changes the operation as intended. Include the wrapper or payload mapping if that is where the wrong name entered the call. Test through that boundary as well as calling the destination directly.

If tests use substitutes, RSpec’s verifying instance doubles check positional and keyword signatures when the real class is available. This is a documentation-based recommendation. The examples here ran on official Ruby 4.0.0 WASI; no RSpec suite, native gem or deployed application was executed.

Do not rescue the entire operation and retry after discarding keywords. A deeper call may fail after earlier work has completed, so retrying can repeat that work. Locate the rejecting method, correct its caller deliberately and keep a focused test at that boundary. Check the intended result as well as the error.

Takeaway

To fix a Ruby unknown keyword argument error, compare the rejected name with the actual receiving signature. Correct misspellings, map payloads deliberately and route options to their owners. Add support only when the method should implement that behavior. Finally, verify results alongside the absence of an exception.