DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Print List Content In Vertical Table

12.20.2010
| 3008 views |
  • submit to reddit
        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 "<tr><td>" + data.join("</td><td>") + "</td></tr>" 
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("</"+name+">") 
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)