Ruby ArgumentError: Diagnose and Fix Invalid Calls

Diagnose wrong argument counts, missing or unknown keywords, and invalid values with tested Ruby examples and a keyword-binding exercise.

Written by Technically reviewed by Jim Freeze · Reviewed

A Ruby ArgumentError means a call used arguments that the receiving operation does not accept. The cause may be the argument count, missing or unknown keywords, or an unacceptable value. Read the full message and backtrace, locate the call, then compare it with the method’s actual declaration. correct that mismatch instead of inventing a default to suppress the exception.

Ruby ArgumentError diagnostic guide separating argument count, keyword names and unacceptable values
Read the error message first: correct the argument count, keyword names or value rule that the call violates.

A Ruby ArgumentError is an exception class, not a complete diagnosis. Two calls can raise it for different reasons. one may omit a required keyword; another may provide the wrong number of positional arguments. Keep the message and backtrace together while reducing the problem to a small example.

Read a Ruby ArgumentError before changing code

Start with the first relevant application location in the backtrace. A method may reject the call before its body runs, or it may raise deliberately during validation. That distinction matters when a breakpoint inside the method never gets reached. Inspect the call site as well as the method definition.

It is likely that your call will reference a method that you do not directly declare. Consider an inherited method, or wrapper. Such methods can define a different set of accepted arguments than you expect based upon prior experience. Before making any adjustments to your code base, consult the documentation for your current Ruby installation. Further, since dependencies frequently change, consider comparing their documented usage prior to updating multiple callers simultaneously.

Not every argument-related failure raises ArgumentError. An incompatible conversion may raise TypeError, while calling an unavailable method can raise NoMethodError. Our article about debugging a nil receiver covers the latter case. Look beyond a familiar line to identify exactly what failed.

Wrong number of positional arguments

A positional parameter receives values based on the order in which they appear. Since this method has defined a single positional argument, making a call without arguments would clearly not satisfy that requirement. The error message describes how many arguments were received versus how many the method expected. Including the required name will resolve this example without modifying the method’s behavior.

def greeting(name)
  "Hello, #{name}"
end
begin
  greeting
rescue ArgumentError => error
  puts error.message
end
puts greeting("Ada")
# wrong number of arguments (given 0, expected 1)
# Hello, Ada

If the omitted value is truly optional, providing a default based upon documentation could be appropriate. However, adding a default simply to suppress exceptions can mask a caller that forgot to include required information. Determine if omission is allowable first, and then reflect that decision within the signature and tests.

Additionally, verify whether an array was intended to represent one argument or multiple. An array passed as normal takes up one positional slot; however expanding it passes each element individually. Neither form is universally correct. Ensure that you align the receiving signature with the way you intend for callers to package their values.

Ruby ArgumentError with keyword arguments

keyword parameters receive named values. A required keyword has no default, therefore omitting it results in an error. Similarly, an unrecognized keyword can also result in an error, particularly if the method does not accept such a key. Verify the spelling of the keyword name, as well as whether it is singular vs plural. Additionally, verify whether a wrapper properly forwarded all of the same keywords it received.

def label(name:)
  "Name: #{name}"
end
begin
  label
rescue ArgumentError => error
  puts error.message
end
begin
  label(name: "Ada", color: "blue")
rescue ArgumentError => error
  puts error.message
end
puts label(name: "Ada")
# missing keyword: :name
# unknown keyword: :color
# Name: Ada

Modern Ruby separates positional hashes from keyword arguments. Therefore, if your options are represented as a hash and the method accepts keywords, you probably need to explicitly expand them as keywords. Do not blindly apply that change to a method that intentionally accepts one positional hash.

options = {name: "Ada"}
puts label(**options)
# Name: Ada

These examples use Ruby 4.0.0. Previous versions of Ruby, as well as compatibility wrappers may behave differently regarding keyword conversions. When migrating across versions, verify that the same call behaves similarly on all of the versions involved and examine the wrapper’s signature. Examples are not proof that migrating an entire application is compatible.

Correct argument count, unacceptable value

A call can supply exactly the proper amount of arguments and yet still fail a value constraint. For example, requesting an array’s negative number of leading entries is invalid. Simply increasing or decreasing the count of arguments will not solve this problem; you must validate or adjust the value itself.

items = ["red", "green", "blue"]
begin
  items.first(-1)
rescue ArgumentError => error
  puts error.message
end
p items.first(2)
# negative array size
# ["red", "green"]

Locate the origin of the invalid count. Subtracting a number, parsing input or missing a boundary check may cause this issue. Do not clamp all negative numbers to zero unless this is how your product intends to handle such values. Doing so will allow an erroneous calculation to produce a seemingly valid output and hide the true issue.

Message patternFirst checkLikely repair
Wrong number of argumentsPositional count and signatureCorrect the call or documented default
Missing keywordRequired keyword namesSupply the required named value
Unknown keywordAccepted names and forwardingCorrect the name or caller contract
Invalid valueAllowed range or formatValidate or correct the supplied value

Raise Ruby ArgumentError deliberately

You can reject an unacceptable argument within your own methods with a clear message. Identify constraints near a public boundary before making state modifications. Within the following example, we demonstrate a quantity which must be a positive integer; thus excluding zero, negative numbers and strings – regardless of whether such strings happen to contain digits.

def pack_count(quantity)
  unless quantity.is_a?(Integer) && quantity.positive?
    raise ArgumentError, "quantity must be a positive Integer"
  end
  quantity
end
p pack_count(3)
begin
  pack_count(0)
rescue ArgumentError => error
  puts error.message
end
# 3
# quantity must be a positive Integer

This is a deliberately strict educational policy for demonstration purposes only; other applications may choose to permit zero or parse a text field prior to invoking this method. Always keep parsing and validation decisions explicit. If you permit conversion, specify which formats you support and test malformed input in addition to standard input.

Name the argument and rule it broke in the exception message, without including sensitive payloads. Callers should distinguish an omitted requirement from an internal failure without seeing a complete customer record in the log. Follow the application’s established exception conventions where they already exist.

Rescue only where recovery makes sense

A narrow rescue can translate expected validation failures into meaningful responses. However, wrapping a large operation in an ArgumentError rescue can capture an unrelated nested call programming mistake as well. Limit your protected area so you understand which failure it represents.

The community Ruby style guide suggests avoiding overly broad exception handling in their advice on blind rescues. Catching the right class is only half of that discipline; you must also limit yourself to an operation that can actually recover from errors. Do not return success from silently ignoring required work.

If a method cannot proceed with invalid input, letting its explicit error reach the appropriate boundary can be clearest. A user interface can explain the validation issue; a job runner can record a failed job. Neither should pretend that the original operation completed successfully.

Exercise: which part of the call is wrong?

A method requires keyword name. one caller includes no arguments; another includes name and also an unsupported color keyword. Will adding an optional positional parameter fix both callers? Predict each of these failures; then reveal the explanation. Focus on how values are bound to parameters as opposed to simply counting visible values.

Reveal the keyword diagnosis

No. The first caller fails because it does not provide any value for name as per its keyword requirement; the second caller provides name but also uses an unknown color keyword. An optional positional parameter affects something else entirely relative to your signature. The above example illustrates both error messages; fix each caller consistent with documented names.

Also test a caller that supplies the name correctly and checks the returned label. That successful case matters: rejecting bad calls is not enough if the repair breaks the intended call. Keep the failure cases and the successful case together in the regression suite.

Follow wrappers without hiding the mismatch

Wrappers may forward a valid call while passing the wrong shape down to another method. Inspect both signatures as well as how you are forwarding your call values. A caller may supply valid keyword(s) while an intermediary helper converts those keywords into positional hashes. Changing your final method can mask issues at wrappers and harm otherwise correct callers.

Keep the reproduction small enough to show the handoff. Record the Ruby version and dependency version with the failing call. Then test the public entry point, not just the final helper. The test should show that callers can use the documented interface after the repair.

Test the failure you intended

Assert the intended exception class, and match a stable message when it identifies your own validation rule. The RSpec raise-error matcher documentation shows class and message expectations. An expectation accepting any exception can pass because of an unrelated missing method, leaving the intended behaviour untested.

Test valid and invalid boundaries too. For the positive-quantity example, include one, a larger integer, zero, a negative number and a string. The displayed examples and these quantity checks ran on official Ruby 4.0.0 WASI. RSpec is discussed from documentation; no RSpec suite, native gem or production application execution is claimed.

Takeaway

Fix a Ruby ArgumentError by identifying whether the problem is argument count, keyword binding or an unacceptable value. Compare the actual call with the actual signature, preserve required-data rules, and keep regression tests for the intended result or exception. Rescue only when a specific recovery policy exists.