hashwithindifferentaccess ruby

The "HashWithIndifferentAccess" class in Ruby is a utility class that allows you to access hash keys using either strings or symbols interchangeably. It is commonly used in Rails applications to handle incoming parameters and convert them into a hash that can be accessed in a consistent manner.

Here is an example of how to use HashWithIndifferentAccess in Ruby:

  1. First, you need to require the 'active_support' gem, which provides the implementation for HashWithIndifferentAccess:
require 'active_support/hash_with_indifferent_access'
  1. Next, you can create a new instance of HashWithIndifferentAccess:
params = HashWithIndifferentAccess.new
  1. You can then add key-value pairs to the hash using either strings or symbols as keys:
params[:name] = 'John'
params['age'] = 25
  1. You can access the values in the hash using either strings or symbols:
puts params[:name] # Output: John
puts params['age'] # Output: 25
  1. You can also use methods like fetch or slice on the hash:
puts params.fetch(:name) # Output: John
puts params.slice(:name) # Output: { :name => 'John' }
  1. The HashWithIndifferentAccess class also provides methods like delete, merge, and to_h, which work similarly to regular hashes:
params.delete(:name)
puts params # Output: { 'age' => 25 }

new_params = params.merge({ :city => 'New York' })
puts new_params # Output: { 'age' => 25, :city => 'New York' }

hash = params.to_h
puts hash # Output: { 'age' => 25 }

That's a brief explanation of how to use the HashWithIndifferentAccess class in Ruby. It provides a convenient way to handle hash keys without worrying about whether they are strings or symbols.