Last active
August 29, 2015 14:17
-
-
Save bradland/26d4744ce19766779947 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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