Skip to content

Instantly share code, notes, and snippets.

@tily
Created February 3, 2012 04:51
Show Gist options
  • Save tily/1728148 to your computer and use it in GitHub Desktop.
Save tily/1728148 to your computer and use it in GitHub Desktop.
変数名をキーにしてハッシュを作る
def args_to_hash(*args)
hash = {}
path, line = caller.first.split(':')
File.open(path) do |f|
(line.to_i-1).times { f.readline }
source = f.readline
args_text = source[/args_to_hash\((.+)\)/, 1]
keys = args_text.gsub(/\s/, "").split(',')
keys.each_with_index do |key, i|
hash[key.intern] = args[i]
end
end
hash
end
a, b, c = 'hoge', 2, Time.new
p args_to_hash(a, b, c) # => {:a=>"hoge", :b=>2, :c=>2012-02-03 13:50:39 +0900}
p args_to_hash("hoge", 2, Time.now) # => {:"\"hoge\""=>"hoge", :"2"=>2, :"Time.now"=>2012-02-03 13:50:39 +0900}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment