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")
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.
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" ).
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.
You can just use with_indifferent_access
.
SETTINGS = YAML.load_file("#{RAILS_ROOT}/config/settings.yml").with_indifferent_access
If you have a hash already, you can do:
HashWithIndifferentAccess.new({'a' => 12})[:a]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With