Created
September 14, 2012 09:45
-
-
Save tallakt/3721059 to your computer and use it in GitHub Desktop.
Concept for Hash from table generator
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
class TableHash | |
# creates a Hash from a table structure | |
# | |
# TableHash[ | |
# 4, | |
# :key, :a, :b, :c, | |
# 'first', 10, 11, 12, | |
# 'second', 20, 30, 40 | |
# ] | |
# | |
# => | |
# { | |
# "first" => { | |
# :a => 10, | |
# :b => 11, | |
# :c => 12 | |
# }, | |
# "second" => { | |
# :a => 20, | |
# :b => 30, | |
# :c => 40 | |
# } | |
# } | |
# | |
def self.initialize(*args) | |
columns = args.shift | |
symbols = args[0..(columns - 1)] | |
rows = args[columns..-1] | |
Hash[rows.each_slice(columns).map do |slice| | |
[slice.first, Hash[symbols[1..-1].zip(slice[1..-1])]] | |
end] | |
end | |
class << self | |
alias :'[]' :initialize | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment