From: ale@...
Date: 2001-09-01T19:46:41+09:00
Subject: [ruby-talk:20664] Re: replacing items in arrays
Hello Tobias,
On Sat, 1 Sep 2001, Tobias Reif wrote:
> -----------snip-----------
>
> lines = [["item0-0","item1-0"],["item0-1","item1-1"]]
>
> td_lines = lines.collect do |line|
> line.collect do |item|
> '
' + item + ' | '
> end
> end
>
> tr_lines = td_lines.collect do |line|
> '' + line.to_s + '
'
> end
>
> print tr_lines
>
> -----------snip-----------
>
> Is that the Ruby way to do it? Anyone?
This is an imperative way to do it. I wouldn't dare to call it procedural
way.
Anyway, I like OO to certain useful extend, and I like ruby enabling me to
use OO effectively. Here would be my first stab trying to objectify a
simple table generation.
- Aleksi
class String
def to_html
to_s
end
end
class HTMLTableElement
def initialize(element)
@element = element
end
def to_s
@element
end
def to_html
"" + @element.to_html + " | "
end
end
class HTMLTableRow
def initialize(elements)
@elements = elements
end
def to_s
@elements.join(', ')
end
def to_html
"" + @elements.collect { |elem| elem.to_html }.join('') +
"
\n"
end
end
class HTMLTable
attr_accessor :rows
def initialize(rows = [])
@rows = rows
end
def to_s
@rows.join("\n")
end
def to_html
"\n" + @rows.collect { |row| row.to_html }.join('') +
"
\n"
end
end
table = HTMLTable.new
# later you can easily implement things like:
# table.headers = [HTMLTableHeader.new('foo'), HTMLTableHeader.new('bar')]
pure_text_content = [
['foo1', 'bar1',],
['foo2', 'bar2',],
]
table.rows = pure_text_content.collect do |row|
HTMLTableRow.new(row.collect { |elem| HTMLTableElement.new(elem) })
end
puts "Pure text table:", table
puts "\nHTML table:", table.to_html
####################
And it's output:
Pure text table:
foo1, bar1
foo2, bar2
HTML table: