Skip to content

Instantly share code, notes, and snippets.

@venkatd
Created July 30, 2013 19:51
Show Gist options
  • Save venkatd/6116303 to your computer and use it in GitHub Desktop.
Save venkatd/6116303 to your computer and use it in GitHub Desktop.
Very cool hash builder taken from stack overflow
class HashBuilder
def self.build &block
hb = HashBuilder.new
hb.instance_eval(&block)
hb.hash
end
attr_reader :hash
def initialize
@hash = {}
end
def method_missing meth, *args, &block
@hash[meth] = block ? HashBuilder.build(&block) : args.first
end
end
p HashBuilder.build{
a :b
c :d
e do
f :g
end
}
#=> {:a=>:b, :c=>:d, :e=>{:f=>:g}}
# share|edit|flag
# answered Jul 29 '11 at 13:23
# Mladen Jablanović
# 18.1k23256
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment