Accessing columns by index

Hi,

I have my Find statement returning rows like this
Col1 Col2 Col3 Col4

While displaying I want to do this order: Cyclic fashion.

First row: Col1 Col2 Col3 Col4
Second row: Col2 Col3 Col4 Col1
Third row: Col3 Col4 Col1 Col2
Fourth row: Col4 Col1 Col2 Col3

I thought of doing modulo 4 on column index. But I don't knw how to
access columns by index.

I tried this but with no luck:

@rows = matrx.find(:all)

<% for mat_row in @rows %>

<%= h(truncate(mat_row[i modulo 4], 80)) %>
<%= h(truncate(mat_row[(i + 1)modulo 4], 55)) %>
<%= h(truncate(mat_row[(i+2)modulo 4], 55)) %>
<%= h(truncate(mat_row[(i+3)modulo 4], 55)) %>

<% end %>

Regards,
Sandeep

<% @rows.each_with_index do |mat_row, i| %>
...
<% end %>

Also, if you render the collection with render :partial => 'row', :collection => @rows the index is available in the local variable row_counter.

-- fxn

In addition to Xavier's suggestion (each_with_index), you might add an
array to help you out with accessing the columns:

cols = [:col1, :col2, :col3, :col4]
<% @rows.each_with_index do |mat_row, idx| %>
    <%= h(truncate(mat_row.send cols[i modulo 4], 80)) %>
    <%= h(truncate(mat_row.send cols[(i + 1)modulo 4], 55)) %>
    <%= h(truncate(mat_row.send cols[(i+2)modulo 4], 55)) %>
    <%= h(truncate(mat_row.send cols[(i+3)modulo 4], 55)) %>
<% end %>

The cols array contains the name of the columns (which become
accessors on your ActiveRecord model) in their order for row 1. Here
you use it to provide the name of the column in mat_row, and send
simply invokes the getter.

HTH,
AndyV

<%= h(truncate(mat_row.send cols[i%4], 80)) %>

How would this send invoke a getter? Where are we passing symbol of
getter? I tried direct copy pasting, got syntax error: wrong number of
arguments (1 for 0))

Oh ok. I am sorry my bad. mat_row.send cols[i%4], 80 . IN this 80 is
being taken as argument for send. I got this corrected.

Thanks a lot for solution.
So if no symbol is passed to send, it calls getter?

Regards,
Sandeep G

Sorry. I misplaced a parenthesis.

Actually, you *are* passing a method name (preferably a symbol). The
symbol happens to be stored in the cols array. From the inside out,
you are:

1. Looking up the i+n modulo 4th item in the cols array
2. Invoking send on the result of the look up (thus getting the value
from the nth column as desired).
3. Truncating to the desired length
4. html escaping

AndyV wrote:

Actually, you *are* passing a method name (preferably a symbol). The
symbol happens to be stored in the cols array. From the inside out,
you are:

1. Looking up the i+n modulo 4th item in the cols array
2. Invoking send on the result of the look up (thus getting the value
from the nth column as desired).
3. Truncating to the desired length
4. html escaping

On Feb 19, 1:01 pm, Sandeep Gudibanda <rails-mailing-l...@andreas-

Thanks Andy for the explanation.

Regards,
Sandeep G