Over a million developers have joined DZone.

Ruby HTML Table Helper

 Ruby HTML table helper (generates TD's and TR's) 
 (note, the non-breaking space character in the table function has a typo you must fix, as I couldn't figure out how to escape it)

    :th=>false, :table=>"class='datagrid'")%>

    ['jim','jorgenson'], {:th=>false, :tr=>"border='10'"})%>

  # creates an html table with tr and td tags by passing in args. 
  # Each row is an array.
  # The first gets th tags unless :th=>false is specified
  # options: The last item may be an options hash.  The options 
  # :tr, :td, and :table allow insertion of arbitrary attributes 
  # into the html of their respective tags.
  # If there are rows with too few items the columns are printed as  

 def table(*args)
   opts=args.last.is_a?(Hash) ? args.delete_at(args.length - 1) : {}
   [:table,:tr,:td].each {|sym| opts[sym]= " #{opts[sym]} " if opts[sym]}
   maxcols = rows.inject(0) {|memo,row| row.length > memo ? row.length : memo  }
   rows.map {|row|(maxcols-row.length).times{ row << "& nbsp;"};row }
   rows=rows.map{|row| row.sandwich("\t\t","\n") }
   rows[0].gsub!('td','th') unless opts[:th] == false
   return ("\n" + rows.sandwich("\t\n","\t\n") + "\n")

# Needs:

class Array 
	# wraps the items in the array in a 
	# pre and post string, like ['foo','bar','baz'].sandwich('','')
	# => "foobarbaz"
	def sandwich(str1, str2)
		map{|item| "#{str1}#{item}#{str2}"}.join("")

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}