[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: build 3x3 table from one array

James Gray

3/16/2006 6:03:00 PM

On Mar 16, 2006, at 11:29 AM, forest wrote:

> I am stuck trying to figure out how to take an array of data and
> dynamically build a 3x3 html table from it without standard for loops.

Here's one idea:

>> data = (1..9).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
>> require "enumerator"
=> true
>> puts "<table>"
<table>
=> nil
>> data.each_slice(3) do |row|
?> puts " <tr>"
>> row.each { |cell| puts " <td>#{cell}</td>" }
>> puts " </tr>"
>> end
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
=> nil
>> puts "</table>"
</table>
=> nil

Hope that helps.

James Edward Gray II


4 Answers

forest

3/16/2006 7:46:00 PM

0

Thanks all. The each_slice solution I think will work the best for my
scenario. I really appreciate the help.

forest


> >> data = (1..9).to_a
> => [1, 2, 3, 4, 5, 6, 7, 8, 9]
> >> require "enumerator"
> => true
> >> puts "<table>"
> <table>
> => nil
> >> data.each_slice(3) do |row|
> ?> puts " <tr>"
> >> row.each { |cell| puts " <td>#{cell}</td>" }
> >> puts " </tr>"
> >> end

> Hope that helps.
>
> James Edward Gray II

--
Posted via http://www.ruby-....


matthew.moss.coder

3/16/2006 9:10:00 PM

0

> >> require "enumerator"

Is this standard library?

I tried 'ri Enumerator' to learn more, but it just comes back talking
about SyncEnumerator, which is something else. (Trying the lowercase
'enumerator' didn't work at all.)


Timothy Bennett

3/16/2006 9:21:00 PM

0

Yes, enumerator is part of the standard library. Go to http://ruby-
doc.org/stdlib/ and find enumerator (right after English) in the left
frame if ri isn't helping.

Tim

On Mar 16, 2006, at 1:10 PM, Matthew Moss wrote:

>>>> require "enumerator"
>
> Is this standard library?
>
> I tried 'ri Enumerator' to learn more, but it just comes back talking
> about SyncEnumerator, which is something else. (Trying the lowercase
> 'enumerator' didn't work at all.)
>



Leon Kovalenko

1/28/2008 11:29:00 AM

0

I wrote next function (maybe need to be rewritten to method for Array
cass) -
def array_to_table(arr, width)
data = "<table>"
arr.each_slice(width) do |row|
data << "<tr>"
row.each do |elem|
data << ("<td>" + yield(elem) + "</td>")
end
data << "</tr>"
end
data << "</table>"
end

Using -
<%= array_to_table(User.find(:all), 3) {|user| "<div
id='user_div'>#{user.name}</div>"} %>
--
Posted via http://www.ruby-....