Skip to content

Instantly share code, notes, and snippets.

@rogercampos
Created December 17, 2010 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogercampos/745617 to your computer and use it in GitHub Desktop.
Save rogercampos/745617 to your computer and use it in GitHub Desktop.
Asign a value with an arbitrary deep of keys to a lazy hash. The example shows a use case with i18n keys.
# lazy_hash.rb
module LazyHash
class << self
def lazy_add(hash, key, value, pre = nil)
skeys = key.split(".")
f = skeys.shift
if skeys.empty?
pre.nil? ? hash.send("[]=", f, value) : pre.send("[]=", f, value)
else
pre = pre.nil? ? hash.send("[]", f) : pre.send("[]", f)
lazy_add(hash, skeys.join("."), value, pre)
end
end
def build_hash
lazy = lambda { |h,k| h[k] = Hash.new(&lazy) }
Hash.new(&lazy)
end
end
end
# test.rb
require 'lazy_hash'
foo = LazyHash.build_hash
LazyHash.lazy_add(foo, "es.projects.index.phrase", "Some sentence")
LazyHash.lazy_add(foo, "es.projects.title", "Title")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment