- Published
- Author
- Nitturu BabaSystem Analyst
Ruby hashes treat strings and symbols as different keys.
But JSON data (JWT, APIs) always comes with string keys.
This silently breaks code when Rails-style symbol access is used.
We can use
You no longer care whether keys are strings or symbols. Rails
#Rails
But JSON data (JWT, APIs) always comes with string keys.
Code
decoded = { "user_id" => 1 }
decoded[:user_id] # => nil ❌
decoded["user_id"] # => 1This silently breaks code when Rails-style symbol access is used.
We can use
HashWithIndifferentAccess which removes this mismatch:Code
payload = HashWithIndifferentAccess.new(decoded)
payload[:user_id] # => 1
payload["user_id"] # => 1You no longer care whether keys are strings or symbols. Rails
params works the same way internally.HashWithIndifferentAccess is a class provided by ActiveSupport, so it exists only in Rails, not in core Ruby. It internally normalizes all keys (by storing them as strings) while allowing access using either symbols or strings. It’s designed specifically for boundary data—like JSON responses, JWT payloads, and request params—where key formats are inconsistent. By removing the need to care about key types, it prevents subtle nil bugs without forcing changes in how the rest of the code is written, which is why Rails uses it internally for params#Rails