Skip to content

Instantly share code, notes, and snippets.

@minaguib
Created August 27, 2009 20:08
Show Gist options
  • Save minaguib/176525 to your computer and use it in GitHub Desktop.
Save minaguib/176525 to your computer and use it in GitHub Desktop.
#
# 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