Keyword arguments in Ruby 3: positional/keyword separation

suggest change

Ruby 2.0 introduced keyword arguments, but under the hood they were still a hash passed as the last argument. Ruby converted between the two automatically: a hash at the end of a call could fill keyword parameters, and keywords could end up in a positional hash parameter. That was convenient most of the time and confusing the rest of the time, especially for methods with optional arguments and for code that forwards arguments.

Ruby 3.0 separated them. Keyword arguments are now a separate kind of argument, just like a block is. The main rule is short:

A hash passed as a positional argument is never turned into keyword arguments. To pass a hash as keywords, use **hash.

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

opts = {name: "Ada", greeting: "Hi"}

puts greet(name: "Ada")
puts greet(**opts)
begin
  greet(opts)
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
Hello, Ada!
Hi, Ada!
ArgumentError: wrong number of arguments (given 1, expected 0; required keyword: name)

In Ruby 2.6 greet(opts) worked silently. Ruby 2.7 still accepted it but printed warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call. Since 3.0 it's an ArgumentError. The error message is the hint: the method was given 1 positional argument and expected 0.

All examples below were run with Ruby 4.0. The separation rules haven't changed since 3.0, so the code behaves the same on any Ruby 3.x.

What counts as keywords at the call site

Whether an argument is a keyword argument is decided by how the call is written, not by the type of the value:

def show(*args, **kw) = p(args:, kw:)

opts = {verbose: true}
show(1, verbose: true)     # keywords
show(1, **opts)            # keywords from a hash
show(1, {verbose: true})   # braces: a positional hash
show(1, opts)              # a variable: a positional hash
{args: [1], kw: {verbose: true}}
{args: [1], kw: {verbose: true}}
{args: [1, {verbose: true}], kw: {}}
{args: [1, {verbose: true}], kw: {}}

key: value pairs without braces and **hash are keywords. Anything else, including a hash literal in braces, is a positional argument. In Ruby 2.x the braces made no difference. Now they are the way to say "this is one hash argument".

The conversion that still exists

One direction of the old conversion was kept on purpose, because a huge amount of code depends on it: if a method doesn't accept keywords, keywords passed to it are collected into a positional hash. Methods written before keyword arguments existed, with a trailing options = {} parameter, keep working:

def configure(options = {})
  p options
end

configure(debug: true)
configure({debug: true})
configure

def collect(*args) = p(args)
collect(1, level: 2)
{debug: true}
{debug: true}
{}
[1, {level: 2}]

So the rules are asymmetric:

Call Method accepts keywords Method doesn't accept keywords
m(k: 1) or m(**h) keywords converted to a positional hash
m({k: 1}) or m(h) positional hash (no conversion) positional hash

A method "accepts keywords" if it declares any keyword parameter (k:, k: 1) or **kw. The conversion is what makes the next pitfall possible.

Common errors and how to fix them

Passing an options hash to a keyword method

The greet(opts) error above is the most common one. The fix is always to add ** at the call site: greet(**opts). If the hash comes from outside (parsed JSON, a config file) and has string keys, convert them first, see string keys below.

Optional positional hash plus keywords

When a method has both an optional positional hash and keyword parameters, keywords in a call go to the keyword parameters, never to the hash. A call that only uses bare key: value pairs can now fail with "unknown keyword":

def render(template, locals = {}, layout: true)
  "#{template} locals=#{locals} layout=#{layout}"
end

puts render("home", {title: "Hi"})
puts render("home", {title: "Hi"}, layout: false)
puts render("home", layout: false)
puts render("home", title: "Hi")
home locals={title: "Hi"} layout=true
home locals={title: "Hi"} layout=false
home locals={} layout=false
s04.rb:1:in 'Object#render': unknown keyword: :title (ArgumentError)

    caller: s04.rb:8
    | puts render("home", title: "Hi")
           ^^^^^^
    callee: s04.rb:1
    | def render(template, locals = {}, layout: true)
          ^^^^^^
	from s04.rb:8:in '<main>'

In Ruby 2.x the last call split the hash: layout: went to the keyword and everything else into locals. Ruby 3 doesn't guess. Wrap the hash in braces. This is the case where braces are required, and why APIs that take both a data hash and options are clearer when the data is never the last argument or is always a required positional argument.

Keywords where a positional hash is required

The reverse also fails. If a method has a required positional parameter and also accepts keywords, bare keywords don't fill the positional parameter:

def wrap(value, **options) = p([value, options])

wrap({a: 1})
begin
  wrap(a: 1)
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
[{a: 1}, {}]
ArgumentError: wrong number of arguments (given 0, expected 1)

Again, braces fix it: wrap({a: 1}).

Delegating with *args only

This is the change that broke the most library code. A wrapper written as def m(*args, &block) = target(*args, &block) used to forward keywords, because they rode along as a trailing hash and were converted back. In Ruby 3 the wrapper itself doesn't accept keywords, so they get collected into a hash in args, and that hash is passed on positionally:

def target(*args, **kw) = p(args:, kw:)

def old_wrapper(*args, &block)
  target(*args, &block)
end

def new_wrapper(*args, **kw, &block)
  target(*args, **kw, &block)
end

old_wrapper(1, mode: :fast)
new_wrapper(1, mode: :fast)
new_wrapper(1, {mode: :fast})
new_wrapper(1)
{args: [1, {mode: :fast}], kw: {}}
{args: [1], kw: {mode: :fast}}
{args: [1, {mode: :fast}], kw: {}}
{args: [1], kw: {}}

new_wrapper forwards exactly what it got: keywords stay keywords, a positional hash stays positional, and no keywords means no keywords. In modern Ruby the shorter spellings def m(...) = target(...) and def m(*, **, &) = target(*, **, &) do the same thing. They're described in argument forwarding and anonymous parameters.

**opts vs. a trailing hash parameter

Both def m(opts = {}) and def m(**opts) give you a hash inside the method, but they behave differently for callers:

def m(opts = {}) def m(**opts)
m(a: 1) {a: 1} {a: 1}
m({a: 1}) {a: 1} ArgumentError
m(h) h itself (same object) ArgumentError
m(**h) a copy of h a copy of h
Can be combined with other keywords no, they'd take the keywords yes: def m(a:, **rest)
Shows up in Method#parameters as [:opt, :opts] [:keyrest, :opts]

New code should prefer keyword parameters: named ones when you know the options (they're validated, documented by the signature, and can be required), and **opts when you really accept arbitrary keywords. An options = {} parameter is still fine if the hash is genuinely data, like the attributes of a record, and you want callers to be able to pass an existing hash object without **.

Two smaller changes made ** behave more like a real separate argument kind:

def call_with(*args, **kw) = p(args:, kw:)

empty = {}
call_with(**empty)
call_with(1, **{})
call_with("content-type" => "json", 1 => :one, sym: true)
{args: [], kw: {}}
{args: [1], kw: {}}
{args: [], kw: {"content-type" => "json", 1 => :one, sym: true}}

String keys and merging keywords

Named keyword parameters still only match symbol keys. When options come from JSON or a form, convert the keys first:

def fetch(url, timeout: 30, retries: 0)
  "#{url} timeout=#{timeout} retries=#{retries}"
end

defaults = {timeout: 5, retries: 2}
puts fetch("/a", **defaults, timeout: 1)   # later wins: timeout 1
puts fetch("/a", timeout: 1, **defaults)   # later wins: timeout 5
puts fetch("/a", **defaults.except(:retries))

params = {"timeout" => 1}                  # e.g. parsed from JSON
begin
  fetch("/a", **params)
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
puts fetch("/a", **params.transform_keys(&:to_sym))
/a timeout=1 retries=2
/a timeout=5 retries=2
/a timeout=5 retries=0
ArgumentError: unknown keyword: "timeout"
/a timeout=1 retries=0

Several ** splats and literal keywords can be combined in one call, and the last occurrence of a key wins. That's a handy way to apply defaults (**defaults, **user_opts) without building a merged hash first. Writing the same literal key twice, like fetch("/a", timeout: 1, timeout: 2), is caught by the parser with a duplicate key warning.

** isn't limited to hashes. Any object with a to_hash method can be splatted, but it's never converted implicitly:

def connect(host:, port: 5432) = puts("#{host}:#{port}")

class Settings
  def initialize(**values) = @values = values
  def to_hash = @values
end

settings = Settings.new(host: "db.local", port: 6543)
connect(**settings)
begin
  connect(settings)
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
db.local:6543
ArgumentError: wrong number of arguments (given 1, expected 0; required keyword: host)

In Ruby 2.x an object responding to to_hash passed as the last argument could be turned into keywords. That was a well-known source of surprises, and it's gone.

Rejecting keywords with **nil

Sometimes you want the opposite: a method that must not accept keywords at all. Declaring **nil (Ruby 2.7+) says so explicitly:

def area(width, height, **nil)
  width * height
end

p area(2, 3)
begin
  area(2, 3, unit: :cm)
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
p method(:area).parameters

def store(record = {}, **nil) = p(record)
store({id: 1})
begin
  store(id: 1)
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
6
ArgumentError: no keywords accepted
[[:req, :width], [:req, :height], [:nokey]]
{id: 1}
ArgumentError: no keywords accepted

The second method shows the real use: **nil turns off the keywords-to-positional-hash conversion. store takes a hash, and callers have to pass it as a hash with braces. That's useful when the hash is data and treating store(id: 1) as options would be a mistake, or when you want to reserve the possibility of adding real keyword parameters later without changing what existing calls mean.

Since Ruby 3.4 **nil is also allowed in a call, where it passes no keywords. That makes a splat of an optional hash safe without || {}:

def send_mail(to, subject:, **headers) = p([to, subject, headers])

extra = nil
send_mail("ada@example.com", subject: "Hi", **extra)
extra = {"X-Priority" => "1"}
send_mail("ada@example.com", subject: "Hi", **extra)
["ada@example.com", "Hi", {}]
["ada@example.com", "Hi", {"X-Priority" => "1"}]

On Ruby 3.3 and older, **extra with extra = nil raises TypeError; write **(extra || {}) there.

ruby2_keywords for delegation in libraries

Libraries that had to run on both Ruby 2.x and 3.x couldn't use **kw for delegation: in Ruby 2.6, **kw with an empty hash still passed {} positionally, and ... only arrived in 2.7. Ruby 2.7 added ruby2_keywords as a bridge. It marks a method that takes *args, and when such a method is called with keywords, the hash collected at the end of args gets a hidden flag. Splatting *args into another call passes a flagged final hash as keywords again:

class Mailer
  def deliver(to, subject:, cc: nil) = "to=#{to} subject=#{subject} cc=#{cc.inspect}"
end

class Notifier
  def initialize = @mailer = Mailer.new

  def deliver(*args, &block)
    p Hash.ruby2_keywords_hash?(args.last)
    @mailer.deliver(*args, &block)
  end
  ruby2_keywords(:deliver) if respond_to?(:ruby2_keywords, true)
end

n = Notifier.new
puts n.deliver("ada@example.com", subject: "Hi")
begin
  n.deliver("ada@example.com", {subject: "Hi"})
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
true
to=ada@example.com subject=Hi cc=nil
false
ArgumentError: wrong number of arguments (given 2, expected 1; required keyword: subject)

The if respond_to?(:ruby2_keywords, true) guard was the standard idiom for gems that also supported Ruby 2.6 and older, where the method doesn't exist. Only a hash that arrived as keywords is flagged, so a positional hash still stays positional, as the second call shows.

The flag is fragile. It only survives as long as the very same hash object is the last element of the splatted array, and every method along the delegation chain needs ruby2_keywords:

def target(*args, **kw) = p(args:, kw:)

ruby2_keywords def outer(*args) = middle(*args)
def middle(*args) = target(*args)              # not flagged

ruby2_keywords def outer_ok(*args) = middle_ok(*args)
ruby2_keywords def middle_ok(*args) = target(*args)

ruby2_keywords def outer_copy(*args)
  target(*args[0..-2], args.last.dup)          # dup drops the flag
end

outer(1, k: 2)
outer_ok(1, k: 2)
outer_copy(1, k: 2)
{args: [1, {k: 2}], kw: {}}
{args: [1], kw: {k: 2}}
{args: [1, {k: 2}], kw: {}}

The flag also doesn't help if the hash is passed explicitly instead of through *args. You can create a flagged hash by hand with Hash.ruby2_keywords_hash(h) and check one with Hash.ruby2_keywords_hash?(h), and blocks passed to define_method can be marked with Proc#ruby2_keywords. These exist for code like method_missing proxies that store arguments and replay them later.

All Ruby versions that still matter support ... (2.7+) and *, **, & (3.2+), and Ruby 2.x reached end of life years ago. Use ruby2_keywords only to keep existing code working, and write new delegation with ... or explicit *args, **kwargs, &block.

Blocks, procs and lambdas

Lambdas follow exactly the same rules as methods. Non-lambda procs and blocks are more forgiving, as they are with positional arguments, but they don't convert a positional hash into keywords either:

pr = proc { |a, b: 0| p [a, b] }
la = ->(a, b: 0) { p [a, b] }

pr.call(1, b: 2)
pr.call(1, {b: 2})       # extra positional hash is dropped
la.call(1, b: 2)
begin
  la.call(1, {b: 2})
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
[1, 2]
[1, 0]
[1, 2]
ArgumentError: wrong number of arguments (given 2, expected 1)

The proc silently ignores the extra argument, which makes this bug harder to spot than with a lambda. The same applies to yield: yielding keywords fills a block's keyword parameters, yielding a hash doesn't:

def each_option
  yield :verbose, enabled: true
  yield({name: :quiet, enabled: false})
end

each_option { |name, enabled: nil| p [name, enabled] }
each_option { |*args, **kw| p [args, kw] }

rows = [{id: 1, name: "Ada"}, {id: 2, name: "Bob"}]
rows.each { |row| p row }
begin
  rows.each { |id:, name:| p [id, name] }
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
rows.each { |row| row => {id:, name:}; p [id, name] }
[:verbose, true]
[{name: :quiet, enabled: false}, nil]
[[:verbose], {enabled: true}]
[[{name: :quiet, enabled: false}], {}]
{id: 1, name: "Ada"}
{id: 2, name: "Bob"}
ArgumentError: missing keywords: :id, :name
[1, "Ada"]
[2, "Bob"]

Iterating over an array of hashes with |id:, name:| doesn't work, because each yields each hash as a positional argument. To pull keys out of a yielded hash, use pattern matching (row => {id:, name:}) or row.values_at(:id, :name).

Struct, Data and super

Struct.new classes accept both positional and keyword arguments since Ruby 3.2, without keyword_init: true. The separation rules decide which one you get:

Point = Struct.new(:x, :y)
p Point.new(1, 2)
p Point.new(x: 1, y: 2)           # keywords work without keyword_init (3.2+)
p Point.new({x: 1, y: 2})         # a positional hash is just the first member

StrictPoint = Struct.new(:x, :y, keyword_init: true)
p StrictPoint.new(x: 1, y: 2)
begin
  StrictPoint.new(1, 2)
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end

PosPoint = Struct.new(:x, :y, keyword_init: false)
p PosPoint.new(x: 1, y: 2)        # keywords become one positional hash
p [Point.keyword_init?, StrictPoint.keyword_init?, PosPoint.keyword_init?]

Coord = Data.define(:lat, :lng)
attrs = {lat: 52.2, lng: 21.0}
p Coord.new(**attrs)
begin
  Coord.new(attrs)
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
#<struct Point x=1, y=2>
#<struct Point x=1, y=2>
#<struct Point x={x: 1, y: 2}, y=nil>
#<struct StrictPoint x=1, y=2>
ArgumentError: wrong number of arguments (given 2, expected 0)
#<struct PosPoint x={x: 1, y: 2}, y=nil>
[nil, true, false]
#<data Coord lat=52.2, lng=21.0>
ArgumentError: missing keyword: :lng

A bare super (no parentheses) passes the current method's parameters on with their kinds intact: positional parameters positionally, keyword parameters and ** as keywords. With explicit arguments you choose, and Ruby 3.1's shorthand color: keeps it short:

class Shape
  attr_reader :name, :color

  def initialize(name, color: :black)
    @name, @color = name, color
  end
end

class Square < Shape
  def initialize(name, side, color: :red)
    @side = side
    super(name, color:)
  end
end

class Circle < Shape
  def initialize(name, color: :blue, **)
    super                                # passes name, color: and **
  end
end

[Square.new("sq", 3), Circle.new("c"), Circle.new("c", color: :green)].each do |s|
  p [s.class, s.name, s.color]
end
[Square, "sq", :red]
[Circle, "c", :blue]
[Circle, "c", :green]

super passes the current values of the parameters, so the subclass default color: :blue reaches Shape#initialize even when the caller didn't pass it.

Migrating old code

Most code needs no changes: calls with literal key: value pairs and methods with options = {} behave as before. When upgrading code that predates Ruby 3, look for these patterns:

  1. Hash variables passed to keyword methods: m(opts) becomes m(**opts). The error is "wrong number of arguments (given N, expected N-1...)", often with "required keyword" in the message.
  2. Delegating wrappers with only *args: def m(*args, &b) = other(*args, &b) becomes def m(...) = other(...), or add **kwargs. This includes method_missing, send/public_send wrappers and define_method with |*args|.
  3. Methods with an optional hash and keywords: callers that relied on the split need braces around the hash.
  4. Blocks yielding hashes into keyword parameters: destructure the hash explicitly.
  5. Mocks and stubs: test doubles that record *args and compare them with with(a: 1) may see a positional hash instead of keywords. Current RSpec and Minitest distinguish the two, so a failing expectation can point to a real separation bug in the code under test.

Ruby 2.7 printed a deprecation warning for every one of these cases, so if you still have a 2.7 environment, running the test suite there with -W:deprecated (or Warning[:deprecated] = true) lists them. On Ruby 3.x they are plain ArgumentErrors, or, for wrappers that pass a hash to a method that also accepts one positionally, silent changes in behavior, which is why the delegation patterns deserve a careful look.

Quick reference

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents