Skip to content

Instantly share code, notes, and snippets.

@lnaia
Last active June 3, 2017 23:00
Show Gist options
  • Save lnaia/cba72ccf72481967e6395a2b3b4976c3 to your computer and use it in GitHub Desktop.
Save lnaia/cba72ccf72481967e6395a2b3b4976c3 to your computer and use it in GitHub Desktop.
Transpose hash to rows and expand to match max element count.
def transpose_rows(hash)
separator = ' '
rows = []
rows << hash.keys.join(separator) # header
all = []
max_elements = 0
hash.each do |_, arr|
all << arr
max_elements = arr.length if arr.length > max_elements
end
all.map! { |arr| expand(arr, max_elements) }
rest = all.slice(1, all.length)
all.first.zip(*rest).each { |row| rows << row.join(separator) }
rows
end
def expand(arr, max_elements, default = 0)
size = max_elements - arr.length
arr.concat(Array.new(size, default.to_i))
end
data = {
a: %w(a b c),
b: [1, 2, 3, 4, 5],
c: [9, 8, 7, 6, 44, 33, 22]
}
transpose_rows(data)
#[
# [0] "a b c",
# [1] "a 1 9",
# [2] "b 2 8",
# [3] "c 3 7",
# [4] "0 4 6",
# [5] "0 5 44",
# [6] "0 0 33",
# [7] "0 0 22"
#]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment