Skip to content

Instantly share code, notes, and snippets.

@bradland
Last active August 29, 2015 14:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradland/26d4744ce19766779947 to your computer and use it in GitHub Desktop.
Save bradland/26d4744ce19766779947 to your computer and use it in GitHub Desktop.
# Allows access to deep hashes by passing an array of keys, which will be used
# in a serial chain of hash key lookups. For example, the array:
# [:one, :two, :three]
# Would translate to the key structure:
# hash[:one][:two][:three]
# Usage:
# {one: {two: {three: 'bar'} } }.ary_access [:one, :two, :three] # => 'bar'
# By passing two arguments, you can assign a value to the specified hash key and
# get the value in return:
# {one: {two: {three: 'bar'} } }.ary_access [:one, :two, :three], 'baz' # => 'baz'
module HashArrayAccess
def ary_access(keys, value=nil)
keys = keys.dup
if keys.size > 1
hash = self[keys.shift]
hash.ary_access(keys, value)
else
if value
self[keys.shift] = value
else
self[keys.shift]
end
end
end
end
# Include HashArrayAccess in Hash to add the ary_access method
class Hash; include HashArrayAccess; end
def sep; puts "\n"; end
hash = {one: {two: {three: 'bar'} } }
keys = [:one, :two, :three]
puts "Hash, keys:"
puts "#{hash.inspect}, #{keys.inspect}"
puts "hash.ary_access keys"
p hash.ary_access keys
sep
puts "Hash, keys:"
puts "#{hash.inspect}, #{keys.inspect}"
puts "p hash.ary_access keys, \"baz\""
p hash.ary_access keys, "baz"
sep
puts "Hash, keys:"
puts "#{hash.inspect}, #{keys.inspect}"
puts "p hash.ary_access keys"
p hash.ary_access keys
sep
puts "Hash:"
p hash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment