Using HashWith Indifferent Access in Ruby and Rails
Meet The More Indifferent Hash
2 min readApr 12, 2023
ActiveSupport::HashWithIndifferentAccess
is a special type of Ruby hash provided by the Rails ActiveSupport library. It allows you to access hash values using either symbols or strings as keys interchangeably. This can be quite useful in Rails applications, where parameters from various sources (e.g., HTTP requests) may be passed around as strings or symbols.
Here’s a basic example of how to use ActiveSupport::HashWithIndifferentAccess
:
require 'active_support/core_ext/hash/indifferent_access'
# Create a new HashWithIndifferentAccess
indifferent_hash = ActiveSupport::HashWithIndifferentAccess.new
# Set values using symbols or strings as keys
indifferent_hash[:foo] = "bar"
indifferent_hash["baz"] = "qux"
# Access values using symbols or strings as keys interchangeably
puts indifferent_hash[:foo] # Output: "bar"
puts indifferent_hash["foo"] # Output: "bar"
puts indifferent_hash[:baz] # Output: "qux"
puts indifferent_hash["baz"] # Output: "qux"
Here’s an example using Rails parameters:
# Assuming you have the following parameters in a Rails controller action:
params = ActionController::Parameters.new({ "controller" => "example", "action" => "index", :name => "John Doe", "age" => 30 })
# You can convert the parameters to a HashWithIndifferentAccess
indifferent_params = params.permit(:name, :age).to_h.with_indifferent_access
# Now you can access the parameters using symbols or strings as keys interchangeably
puts indifferent_params[:name] # Output: "John Doe"
puts indifferent_params["name"] # Output: "John Doe"
puts indifferent_params[:age] # Output: 30
puts indifferent_params["age"] # Output: 30