Created
August 27, 2009 20:08
-
-
Save minaguib/176525 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# | |
# This class allows you to easily set/default/increment a value in an arbitrarily-deep hash | |
# using a single (slash)-delimited string | |
# | |
class HashSlash < Hash | |
def slash_set(key, value, value_set_mode = :override) | |
parts = key.split("/") | |
h = self | |
parts.each_with_index do |part, i| | |
if i == parts.length - 1 | |
# Last one | |
case value_set_mode | |
when :default | |
h[part] ||= value | |
when :increment | |
h[part] ||= 0 | |
h[part] += value | |
else | |
h[part] = value | |
end | |
else | |
h[part] ||= {} | |
h = h[part] | |
end | |
end | |
value | |
end | |
end | |
# | |
# Usage example | |
# | |
h = HashSlash.new | |
h.slash_set("customers/Bob/address/street1", "234 Meadowland") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment