Display data in columns not rows using Ruby on Rails

前端 未结 4 1125
慢半拍i
慢半拍i 2020-12-10 10:01

I would like to display data in Columns rather than Rows in my web page.

What is the most efficient way to do this using Ruby on Rails?

Many thanks for your

4条回答
  •  甜味超标
    2020-12-10 10:16

    Adapted from an earlier, similar question/answer:

    def rotate(matrix)
      columns = matrix.first.size
      rows = matrix.size
      result = []
      columns.times { |y|
        result[y] = []
        rows.times { |x|
          result[y][x] = matrix[x][y]
        }
      }
      result
    end
    

    I believe this may be called "transposition," since rather than rotating the array, you really just want to make row 1 into column 1 and so forth. That is, if you rotated a quarter-turn counterclockwise, array[0][0] would wind up in the lower left-hand corner. The above implementation assumes you still want [0][0] to remain in the upper left:

    1 2 3 4
    5 6 7 8
    9 0 a b
    
    1 5 9
    2 6 0
    3 7 a
    4 8 b
    

    I'm also assuming all of the rows have the same number of elements/columns.

    Oh hey, and wouldn't you know it: Array#transpose...

    <%= render :partial => 'mytable', :collection => @array.transpose %> # untested
    

提交回复
热议问题