Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

DZone's Guide to

# Print List Content In Vertical Table

·
Free Resource

Comment (0)

Save
{{ articles[0].views | formatCount}} Views
```print each item of list in table, verticaly in place of horizontaly :

```
class Array
def  print_vtable( nbcol)
nb_line=(self.length+nbcol-1)/nbcol;
0.upto(nb_line-1) {  | noline |
s=[]
0.upto(nbcol-1) { | nocol |
index=noline+nocol*nb_line
s << self[index].to_s   if index< self.length
}
puts s.join("  ")
}
end
end

(1..10).to_a.print_vtable ( 4)

1 4 7 10
2 5 8 11
3 6 9
```
this is done for ascii output,
but howto make for generic outputing (html,pdf,sql,...) ?

Here one solution :
```
class Array
def  print_vtable nbcol
nb_line=(self.length+nbcol-1)/nbcol;
0.upto(nb_line-1)   do   | noline |
s=[]
0.upto(nbcol-1) { | nocol |
index=noline+nocol*nb_line
s << self[index]   if index< self.length
}
if block_given?
yield s
else
puts s.join("  ")
end
end
end
end

(1..11).to_a.print_vtable ( 4 )  do | data |
puts "" + data.join("") + ""
end
```

And another solution, with Fiber :

```
def vtable(a,nbcol)
Fiber.new do
nb_line=(a.length+nbcol-1)/nbcol;
0.upto(nb_line-1)   do   | noline |
Fiber.yield(:start)
0.upto(nbcol-1) do | nocol |
index=noline+nocol*nb_line
Fiber.yield(a[index])   if index< a.length
end
Fiber.yield(:end)
end
Fiber.yield(nil)
end
end

def tag(name)
STDOUT.write("<"+name+">")
STDOUT.write(yield) rescue p \$!
STDOUT.write("
")
end

def to_html(source)
item=nil
tag("table") {
tag("tr") {
tag("td") { item.to_s  } while (item=source.resume) != :end
} while source.resume
}
end

to_html vtable((1..10).to_a,4)
``````
Topics:

Comment (0)

Save
{{ articles[0].views | formatCount}} Views

Opinions expressed by DZone contributors are their own.