Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to find a way to display an array in a Rails view as follows:

 [  1  ] [  4  ] [  7  ] [  10  ]
 [  2  ] [  5  ] [  8  ] [  11  ]
 [  3  ] [  6  ] [  9  ] [  12  ]

In my controller, I have an array defined as

 def index
 @myArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
 end

Since this display order is not typical for a table, I am unsure how to proceed to accomplishing this.

I would like to know the following:

  1. What's the best way to display the values (above) in a table on my Rails view page using the order that I have requested in the code? Simply looping over the @myArr with <tr> and <td> results in the following:

    [  1  ] [  2  ] [  3  ] [  4  ]
    [  5  ] [  6  ] [  7  ] [  8  ]
    [  9  ] [  10 ] [  11 ] [  12 ]
    

Thanks in advance for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
223 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you want to do it in Ruby, then:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].each_slice(3).to_a.transpose.flatten
# => [1, 4, 7, 10, 2, 5, 8, 11, 3, 6, 9, 12]

But I wouldn't do it this way. I would use CSS3 flexbox properties to do it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...