For example:
params['name'] == params[:name]
# => true
However, a normal Hash in Ruby does not allow this:hash = { 'name' => 'Fred' }
hash['name']
# => 'Fred'
hash[:name]
# => nil
hash['name'] == hash[:name]
# => false
We can fix this by making this into a hash with indifferent access:new_hash = hash.with_indifferent_access
new_hash['name'] == new_hash[:name]
# => true
The hash can also be defined/initialized with indifferent access, either by calling that method on the initial hash assignment, or by creating it using ActiveSupport (which is what the with_indifferent_access
method does under the hood anyway):hash = ActiveSupport::HashWithIndifferentAccess.new(name: 'Fred')
hash['name'] == hash[:name]
# => true
Note: When working in straight Ruby, this will not work as it’s using ActiveSupport. One would likely need to run gem install active_support
and require it properly.Source: apidock and RoR api
No comments:
Post a Comment