Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I have a hash in Ruby on Rails, is there a way to make it indifferent access?

If I already have a hash, can I make it so that

h[:foo] h['foo'] 

are the same? (is this called indifferent access?)

The details: I loaded this hash using the following in initializers but probably shouldn't make a difference:

SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml") 
like image 576
Sarah W Avatar asked May 02 '11 19:05

Sarah W


People also ask

Is a Hash an object in Ruby?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.

What is HashWithIndifferentAccess?

HashWithIndifferentAccess is the Rails magic that paved the way for symbols in hashes. Unlike Hash , this class allows you to access data using either symbols ( :key ) or strings ( "key" ).

Is Hash ordered in Ruby?

The C behind the Ruby Add a hashing function on top and you've got yourself a Ruby 1.8 Hash. However, this structure also has no notion of order, which means that a separate structure has to be created if the property is needed in your application - duplicating memory, and adding overhead overall.


2 Answers

You can just use with_indifferent_access.

SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml").with_indifferent_access 
like image 156
Austin Taylor Avatar answered Sep 21 '22 07:09

Austin Taylor


If you have a hash already, you can do:

HashWithIndifferentAccess.new({'a' => 12})[:a] 
like image 27
moritz Avatar answered Sep 24 '22 07:09

moritz