Skip to content

Instantly share code, notes, and snippets.

@tallakt
Created September 14, 2012 09:45
Show Gist options
  • Save tallakt/3721059 to your computer and use it in GitHub Desktop.
Save tallakt/3721059 to your computer and use it in GitHub Desktop.
Concept for Hash from table generator
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