# Solution for ZigZag (Ruby)

• Overall Algorithm

• structure for keeping track of string is in 2d array, with each sub-array in the table corresponding to a row
• write "downwards" all the characters (equivalent to the number of rows)
• write characters diagonally, starting at the bottom
• every time you write a character, check to see that you haven't exceeded the length of the string. Print the result if you have
``````def convert(s, num_rows)
return s if num_rows == 0 or num_rows == 1
return s if s.length <= 1

table = []
for row in 0..(num_rows - 1)
table << []
end

index = 0
len = s.length

while index < len
r = 0
while r < num_rows
table[r] << s[index]
index += 1
r += 1

return get_row_sum(table) if index >= len
end

if num_rows - 2 > 0
for diagonal in 1..(num_rows - 2)
table[num_rows - diagonal - 1] << s[index]
index += 1

return get_row_sum(table) if index >= len
end
end
end

return get_row_sum(table)
end

def get_row_sum(table)
result = ''
table.each do |row|
result += row.join
end

result
end
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.