Created
August 24, 2012 22:27
-
-
Save JakeCoxon/3456453 to your computer and use it in GitHub Desktop.
Ruby to_h
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
### | |
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