Hash and keyword argument shorthand

suggest change

Ruby code often builds a hash or calls a method with keys that have the same names as the local variables holding the values: {name: name, email: email}, connect(host: host, port: port). Ruby 3.1 lets you leave out the value in that case. {name:, email:} means {name: name, email: email}, and connect(host:, port:) passes the local variables host and port as keyword arguments.

This article covers what the shorthand looks up (local variables, methods and constants), how to use it at call sites, in super, and with Data and Struct, how it mirrors pattern matching, the gotcha with method calls written without parentheses, the error messages you get when you misuse it, and RuboCop's settings for it. All examples were run with Ruby 4.0 and RuboCop 1.92. The syntax needs Ruby 3.1 or newer, and older versions reject it with a syntax error.

The basics

Write the key followed by a colon and leave out the value:

name = "Ada Lovelace"
born = 1815
langs = ["Analytical Engine"]

old = {name: name, born: born, langs: langs}
new = {name:, born:, langs:}

p new
p old == new
{name: "Ada Lovelace", born: 1815, langs: ["Analytical Engine"]}
true

The two hashes are identical. The shorthand only changes the source code: the parser expands name: to name: name and the resulting hash is no different from the long form.

The shorthand only works with symbol keys written in key: form (see Creating a hash for the hash syntaxes). It can be mixed freely with explicit values and with ** double splats:

host = "db.internal"
port = 5432
defaults = {pool: 5, timeout: 2.5}

p({host:, port: 6543})                # mix with explicit values
p({host:, port:, **defaults})         # mix with a double splat
p({**defaults, host:, timeout: 10})   # later keys win
p [host:, port:]                      # braces optional as the last array element
{host: "db.internal", port: 6543}
{host: "db.internal", port: 5432, pool: 5, timeout: 2.5}
{pool: 5, timeout: 10, host: "db.internal"}
[{host: "db.internal", port: 5432}]

Note the parentheses in p({host:, port: 6543}). Without them, Ruby parses p {host:} as a call to p with a block and reports a syntax error. The same rule applies to any hash literal passed to a method without parentheses.

What the value can be

The name is resolved the same way a bare identifier would be resolved in that position. That means the value can come from a local variable, a method, or (for capitalized names) a constant.

Methods, including private methods and attribute readers

When there is no local variable with that name, key: calls a method with that name on self. Because it's a call without an explicit receiver, private methods work too. This makes to_h methods built from attribute readers very short:

class User
  attr_reader :name, :email

  def initialize(name, email)
    @name = name
    @email = email
  end

  def to_h = {name:, email:, admin:}

  private

  def admin = email.end_with?("@example.com")
end

p User.new("Ada", "ada@example.com").to_h
{name: "Ada", email: "ada@example.com", admin: true}

Local variables win over methods

If a local variable and a method share the name, the local variable wins, just as it does for a bare label in an expression. Whether label is a local variable is decided by the parser: it's a local variable from the point of its first assignment onward, not before. A capitalized key resolves to a constant:

def label = "from method"

p({label:})
label = "from local"
p({label:})

VERSION = "2.1.0"
p({VERSION:})
{label: "from method"}
{label: "from local"}
{VERSION: "2.1.0"}

The first {label:} comes before the assignment, so it calls the method. That's normal Ruby scoping, but it's easier to miss when the name appears only once.

What doesn't work

Instance variables, predicate and bang method names, and quoted keys can't be used with the shorthand. All of these are syntax errors:

class Job
  def initialize = @status = :queued
  def to_h = {@status:}
end
g6.rb:3: syntax errors found (SyntaxError)
  1 | class Job
  2 |   def initialize = @status = :queued
> 3 |   def to_h = {@status:}
    |              ^ expected a `}` to close the hash literal
    |                      ^ unexpected ':', ignoring it
...
def done? = true
p({done?:})
g7.rb:2: syntax error found (SyntaxError)
  1 | def done? = true
> 2 | p({done?:})
    |    ^~~~~ identifier done? is not valid to get
id = 7
p({"id":})
g8.rb:2: syntax error found (SyntaxError)
  1 | id = 7
> 2 | p({"id":})
    |         ^ unexpected '}'; expected a value in the hash literal

For instance variables either write status: @status, or add an attr_reader and use {status:}. A {done?: done?} key has to be written out in full.

A typo in the name is not a syntax error. Ruby treats it as a method call, so it fails at run time:

user_name = "Ada"
p({usr_name:})
g5.rb:2:in '<main>': undefined method 'usr_name' for main (NoMethodError)

p({usr_name:})
   ^^^^^^^^

Keyword arguments at the call site

The same shorthand works when passing keyword arguments, because a keyword argument list is parsed like a hash. Order doesn't matter, and you can mix in explicit values:

def connect(host:, port: 5432, ssl: false)
  "#{ssl ? "postgres+ssl" : "postgres"}://#{host}:#{port}"
end

host = "db.internal"
ssl = true

puts connect(host:)
puts connect(host:, ssl:)
puts connect(ssl:, host:, port: 6543)
postgres://db.internal:5432
postgres+ssl://db.internal:5432
postgres+ssl://db.internal:6543

It also works when you build the arguments as a hash first and pass it with **:

def total(items:, tax:) = items.sum * (1 + tax)

items = [10, 20]
tax = 0.25
args = {items:, tax:}
p total(**args)
p args
37.5
{items: [10, 20], tax: 0.25}

Passing keywords through: wrappers and super

The shorthand shines in code that receives keyword arguments and passes them on under the same names: factory methods, subclasses calling super, and thin wrappers around other APIs. Inside a method, each keyword parameter is a local variable, so name: passes it along:

class Notifier
  def initialize(channel:, retries: 3)
    @channel = channel
    @retries = retries
  end

  def to_s = "#{self.class.name}(#{@channel}, retries=#{@retries})"
end

class SlackNotifier < Notifier
  def initialize(channel:, webhook:, retries: 5)
    super(channel:, retries:)
    @webhook = webhook
  end
end

def build_notifier(kind, channel:, webhook: nil)
  case kind
  when :slack then SlackNotifier.new(channel:, webhook:)
  else Notifier.new(channel:)
  end
end

puts build_notifier(:slack, channel: "#ops", webhook: "https://hooks.example/x")
puts build_notifier(:email, channel: "ops@example.com")
SlackNotifier(#ops, retries=5)
Notifier(ops@example.com, retries=3)

super(channel:, retries:) passes only the two keywords the parent accepts and leaves webhook out. A bare super would pass all three and fail with unknown keyword: :webhook. When you want to forward everything unchanged, use ... or anonymous ** instead (see Capturing undeclared keyword arguments).

Keyword parameters named after reserved words

A less obvious use: keyword parameters can have names that are Ruby keywords, like class: or if:. That is popular in HTML helpers, where class is the natural name. Before 3.1 the only way to read such a parameter was binding.local_variable_get(:class), because class on its own starts a class definition. The shorthand looks the value up by name, so it can read the parameter:

def tag(name, text, **attrs)
  html_attrs = attrs.compact.map { |k, v| %( #{k}="#{v}") }.join
  "<#{name}#{html_attrs}>#{text}</#{name}>"
end

# Before 3.1: `class` is a keyword, so the parameter can't be read directly
def link_to_old(text, href:, class: nil)
  tag(:a, text, href: href, class: binding.local_variable_get(:class))
end

# Ruby 3.1+: the shorthand looks the parameter up by name
def link_to(text, href:, class: nil)
  tag(:a, text, href:, class:)
end

puts link_to_old("Home", href: "/", class: "nav")
puts link_to("Home", href: "/", class: "nav")
puts link_to("Docs", href: "/docs")
<a href="/" class="nav">Home</a>
<a href="/" class="nav">Home</a>
<a href="/docs">Docs</a>

The gotcha: calls without parentheses

Ruby lets you leave out parentheses around method arguments, and the shorthand lets you leave out a value. Combine the two and the parser doesn't know where the argument list ends. When key: is the last argument of a call without parentheses, Ruby keeps reading on the next line, looking for the value:

def notify(**kw) = puts("notify #{kw}")

user = "ada"
notify user:
puts "done"
g1.rb: --> g1.rb

Unmatched keyword, missing `end' ?

> 1  def notify(**kw) = puts("notify #{kw}")
> 3  user = "ada"
> 4  notify user:
> 5  puts "done"

g1.rb:5: syntax error found (SyntaxError)
  3 | user = "ada"
  4 | notify user:
> 5 | puts "done"
    |      ^ unexpected string literal, expecting end-of-input

Ruby read notify user: puts and then stumbled over "done". The "missing end" hint from syntax_suggest at the top is misleading here. The real problem is on line 4.

A syntax error is the lucky case. If the next line happens to be a valid expression, the code runs and does the wrong thing, with no warning:

def notify(**kw) = puts("notify #{kw}")
def audit(event) = puts("audit #{event}") || :audited

user = "ada"
notify user:
audit(:login)
audit login
notify {user: :audited}

The next line became the value of user:. audit runs first, and notify receives its return value instead of "ada".

The fix is to use parentheses whenever the shorthand comes last in a call. The problem doesn't occur when another argument follows, or when the next token ends the expression (like end or }):

def notify(**kw) = puts("notify #{kw}")
def audit(event) = puts("audit #{event}") || :audited

user = "ada"
notify(user:)
audit(:login)

notify user:, via: :email   # fine: the shorthand isn't last
notify {user: "ada"}
audit login
notify {user: "ada", via: :email}
def login(user)
  notify user:
end

def notify(**kw) = puts("notify #{kw}")
login("ada")
notify {user: "ada"}

This works, but it relies on what happens to come on the next line, and a later edit can break it. The simple rule is: always use parentheses when a call ends with a shorthand argument. RuboCop's autocorrect follows that rule: it rewrites show name: name to show(name:), not to show name:.

Building Data and Struct objects

Data classes accept keyword arguments, and since Ruby 3.2 so does every Struct, even without keyword_init: true. When the values are already in local variables with the member names, the constructor call is just a list of names:

Point = Data.define(:x, :y)
Account = Struct.new(:owner, :balance)

x = 3
y = 4
p Point.new(x:, y:)

owner = "Ada"
balance = 100
p Account.new(owner:, balance:)

# with also takes keywords
y = 10
p Point.new(x:, y: 0).with(y:)
#<data Point x=3, y=4>
#<struct Account owner="Ada", balance=100>
#<data Point x=3, y=10>

Keyword construction is safer than positional construction because swapping two locals can't silently swap the members, and the shorthand makes it as short as Point.new(x, y).

The mirror image of pattern matching

Pattern matching has had the opposite feature since Ruby 3.0: in a hash pattern, {name:} matches the :name key and binds its value to a local variable name. The 3.1 shorthand goes the other way, from locals back to keys. Together they make "take these fields out, check them, put them in a new object" very compact:

User = Data.define(:name, :email)

payload = {name: "Ada", email: "ada@example.com", role: "admin"}

case payload
in {name: String => name, email: /@/ => email}
  user = User.new(name:, email:)
end
p user

# rightward assignment binds locals, the shorthand puts them back
payload => {name:, role:}
p({name:, role:})
#<data User name="Ada", email="ada@example.com">
{name: "Ada", role: "admin"}

payload => {name:, role:} destructures, and {name:, role:} builds the same shape back. It's a readable way to pick out a subset of keys while asserting that they exist. A plain payload.slice(:name, :role) silently drops missing keys, while the pattern raises NoMatchingPatternKeyError.

Style and RuboCop

The shorthand removes repetition, but it also hides where a value comes from: {name:} could be a local, an attribute reader or a private method. Some guidelines that work well in practice:

RuboCop controls this through the EnforcedShorthandSyntax setting of Style/HashSyntax. The default is either, which accepts both forms. The other values are always, never, consistent (all-or-nothing within one hash) and either_consistent. Also set TargetRubyVersion: without a gemspec or .ruby-version, RuboCop 1.92 falls back to parsing as Ruby 2.7 and reports the shorthand as a syntax error (Lint/Syntax: unexpected token tCOMMA).

# frozen_string_literal: true

def connect(host:, port:)
  "#{host}:#{port}"
end

host = 'localhost'
port = 5432
puts connect(host: host, port: port)
puts connect(host:, port: 6543)

With this .rubocop.yml:

AllCops:
  TargetRubyVersion: 4.0
  NewCops: enable
Style/HashSyntax:
  EnforcedShorthandSyntax: consistent
$ rubocop --only Style/HashSyntax style.rb
Inspecting 1 file
C

Offenses:

style.rb:9:20: C: [Correctable] Style/HashSyntax: Omit the hash value.
puts connect(host: host, port: port)
                   ^^^^
style.rb:9:32: C: [Correctable] Style/HashSyntax: Omit the hash value.
puts connect(host: host, port: port)
                               ^^^^
style.rb:10:14: C: [Correctable] Style/HashSyntax: Do not mix explicit and implicit hash values. Include the hash value.
puts connect(host:, port: 6543)
             ^^^^

1 file inspected, 3 offenses detected, 3 offenses autocorrectable

rubocop -a applies these fixes, and as shown earlier it adds parentheses where they're needed to keep the meaning.

Summary

Written Means Notes
{name:} {name: name} local variable if one is defined at that point
{name:} (no local) {name: name()} calls a method on self, private methods included
{VERSION:} {VERSION: VERSION} constant lookup for capitalized names
call(a:, b: 2) call(a: a, b: 2) mixes freely with explicit values and **h
super(a:) super(a: a) pass on selected keyword parameters
tag(class:) reads parameter class replaces binding.local_variable_get(:class)
{@ivar:}, {ok?:}, {"k":} syntax error write the value out
call a: + newline value read from the next line use call(a:)

Available since Ruby 3.1. Use it to cut repetition when names already match, and always add parentheses when a call ends with a shorthand key.

Feedback about page:

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



Table Of Contents