Skip to content

Convert Mash symbol keys with Symbol#name - #613

Merged
dblock merged 1 commit into
hashie:masterfrom
sampokuokkanen:mash-symbol-name-keys
Oct 22, 2026
Merged

dblock merged 1 commit into
hashie:masterfrom
sampokuokkanen:mash-symbol-name-keys

Conversation

@sampokuokkanen

Copy link
Copy Markdown
Contributor

Mash#convert_key turns every symbol key into a string with Symbol#to_s, and Symbol#to_s allocates a new String on each call. So every mash[:key], mash.key?(:key), fetch, delete and write with a symbol key allocates one.

On Ruby 3.0+ this uses Symbol#name instead, which returns the symbol's interned frozen string. That's also what Hash#[]= would have stored for the key, so the stored keys and lookups are the same as before. Ruby 2.7 doesn't have Symbol#name and keeps using Symbol#to_s. String and other keys are unchanged.

Rails made the same change for session keys in rails/rails#59102.

Measured on Ruby 3.3.5:

before after
objects per [] + key? + fetch with symbol keys 5 2

It shows up in gems that read Mash options on every request. In OmniAuth, where strategy options are a Mash, a request that isn't an auth request allocated 163 objects with three strategies before this and 115 after.

The new specs check that symbol keys reach the same entries as their string names through writes, reads, key?, fetch, values_at and delete, and that reading with a symbol key doesn't allocate on CRuby 3.0+.

Mash#convert_key turns every symbol key into a string with Symbol#to_s,
which allocates a new String on each read and write. Symbol#name, on
Ruby 3.0+, returns the symbol's interned frozen string instead, which is
also what Hash#[]= would have stored for the key. Older Rubies keep
using Symbol#to_s.
@github-actions

Copy link
Copy Markdown
Contributor

Danger Report

No issues found.

View run

@dblock

dblock commented Oct 22, 2026

Copy link
Copy Markdown
Member

Thanks, merging. Is it time to drop support for Ruby < 3?

@dblock
dblock merged commit da29028 into hashie:master Oct 22, 2026
13 checks passed
@sampokuokkanen

Copy link
Copy Markdown
Contributor Author

Thanks, yeah, it's probably about time to drop 2.7.

@dblock

dblock commented Oct 23, 2026

Copy link
Copy Markdown
Member

Following up on #613 (comment): opened #622 to drop Ruby 2.7 support and require Ruby 3.0. It removes obsolete version-gated method definitions and Symbol#name fallbacks, updates CI and docs, and runs the relevant specs unconditionally on supported Rubies.

— Copilot, an AI posting on behalf of @dblock.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants