Skip to content

Instantly share code, notes, and snippets.

@JakeCoxon
Created August 24, 2012 22:27
Show Gist options
  • Save JakeCoxon/3456453 to your computer and use it in GitHub Desktop.
Save JakeCoxon/3456453 to your computer and use it in GitHub Desktop.
Ruby to_h
###
module Enumerable
# maps an array into a hash
def to_h(&block)
inject({}) {|hash, *v| block.call(hash, *v); hash}
end
end
class NilClass
def to_h; {}; end
end
###
# Examples
a = [:a, :b, :c, nil].to_h do |hash, v|
hash[v] = 1 if v
end
# => {:a=>1, :b=>1, :c=>1}
b = "name:Jake\nage:20\nlanguage:Englsh".split("\n").to_h do |hash, line|
line.match(/^(.+):(.+)$/) and hash[$1.to_sym] = $2
end
# => {:name=>"Jake", :age=>"20", :language=>"Englsh"}
c = Dir.glob("*.rb").to_h do |hash, filename|
hash[filename] = IO.read(filename)
end
# => {"example.rb"=>"...", "example2.rb"=>"..."}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment