Created
July 30, 2013 19:51
-
-
Save venkatd/6116303 to your computer and use it in GitHub Desktop.
Very cool hash builder taken from stack overflow
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
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