class HashWithIndifferentAccess
def []=(key, value)
hash[:key] = "value"
hash = HashWithIndifferentAccess.new
Assigns a new value to the hash:
def []=(key, value) regular_writer(convert_key(key), convert_value(value)) end
def convert_key(key)
def convert_key(key) key.kind_of?(Symbol) ? key.to_s : key end
def convert_value(value)
def convert_value(value) case value when Hash value.with_indifferent_access when Array value.collect { |e| e.is_a?(Hash) ? e.with_indifferent_access : e } else value end end
def default(key = nil)
def default(key = nil) if key.is_a?(Symbol) && include?(key = key.to_s) self[key] else super end end
def delete(key)
def delete(key) super(convert_key(key)) end
def dup
def dup HashWithIndifferentAccess.new(self) end
def fetch(key, *extras)
def fetch(key, *extras) super(convert_key(key), *extras) end
def initialize(constructor = {})
def initialize(constructor = {}) if constructor.is_a?(Hash) super() update(constructor) else super(constructor) end end
def key?(key)
hash.key? "key" # => true
hash.key? :key # => true
hash["key"] = "value"
hash = HashWithIndifferentAccess.new
Checks the hash for a key matching the argument passed in:
def key?(key) super(convert_key(key)) end
def merge(hash)
Merges the instantized and the specified hashes together, giving precedence to the values from the second hash
def merge(hash) self.dup.update(hash) end
def reverse_merge(other_hash)
Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second.
def reverse_merge(other_hash) super other_hash.with_indifferent_access end
def stringify_keys!; self end
def stringify_keys!; self end
def symbolize_keys!; self end
def symbolize_keys!; self end
def to_hash
def to_hash Hash.new(default).merge(self) end
def to_options!; self end
def to_options!; self end
def update(other_hash)
hash_1.update(hash_2) # => {"key"=>"New Value!"}
hash_2[:key] = "New Value!"
hash_2 = HashWithIndifferentAccess.new
hash_1[:key] = "value"
hash_1 = HashWithIndifferentAccess.new
Updates the instantized hash with values from the second:
def update(other_hash) other_hash.each_pair { |key, value| regular_writer(convert_key(key), convert_value(value)) } self end
def values_at(*indices)
hash.values_at("a", "b") # => ["x", "y"]
hash[:b] = "y"
hash[:a] = "x"
hash = HashWithIndifferentAccess.new
Returns an array of the values at the specified indices:
def values_at(*indices) indices.collect {|key| self[convert_key(key)]} end