Created
May 13, 2010 20:30
-
-
Save dcparker/400422 to your computer and use it in GitHub Desktop.
This file contains 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
def locals(*only, &block) | |
raise ArgumentError, "must include a block" unless block_given? | |
bndng = block.send(:binding) | |
all_locals = eval("local_variables",bndng) - ['_'] | |
locals_hash = Hash[all_locals.map {|l| [l,eval(l,bndng)]}] | |
Hash[locals_hash.select {|k,v| only.include?(v)}] | |
end | |
hi = "hello world" | |
bye = "goodbye world" | |
locals(hi){} #=> {"hi" => "hello world"} | |
locals(hi, bye){} #=> {"hi" => "hello world", "bye" => "goodbye world"} | |
def hash_from_locals(*only, &block) | |
raise ArgumentError, "must include a block" unless block_given? | |
bndng = block.send(:binding) | |
Hash[only.map {|l| [l,eval(l.to_s,bndng)]}] | |
end | |
hash_from_locals(:hi, :bye){} #=> {:hi => "hello world", :bye => "goodbye world"} | |
# Probably the most useful manner... you set some local variables, then you want to build an automatic hash | |
_first_name = "Daniel" | |
_last_name = "Parker" | |
def autohash(&block) | |
raise ArgumentError, "must include a block" unless block_given? | |
bndng = block.send(:binding) | |
all_locals = eval("local_variables",bndng) - ['_'] | |
locals_hash = Hash[all_locals.map {|l| [l,eval(l,bndng)]}] | |
locals_hash.select {|k,v| k.to_s =~ /^_/}.inject({}) {|h,(k,v)| h[k.sub(/^_/,'').to_sym] = v; h} | |
end | |
# Generate an automatic hash from all current local_variables that start with '_' | |
autohash{} #=> {:first_name => "Daniel", :last_name => "Parker"} | |
# I've thought of renaming this to _hash, so you'd call it as "_hash{}" | |
# - or, you might like "_locals{}" better... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment