user2398029
user2398029

Reputation: 6937

Staggering a list of posts into two columns in ruby

I have a list of posts ordered by most recent date of modification. I want to stagger them into two columns to have the two recent modified posts at the top. This code is fairly self explanatory:

posts.each do |post|
  right_column << post if shift
  left_column << post if !shift
  shift = shift ? false : true
end

posts = left_column + right_column

For example, given the input  [1, 2, 3, 4], the goal is to produce [1, 3, 2, 4].

Is there a more elegant/idiomatic way to achieve this in Ruby?

Upvotes: 0

Views: 86

Answers (2)

Andrew Marshall
Andrew Marshall

Reputation: 96954

Use each_slice to get the rows, then transpose it into columns, then flatten them:

posts = (1..10).to_a  #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

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

Or, to get the left and right columns separately:

left, right = posts.each_slice(2).to_a.transpose

Upvotes: 4

Borodin
Borodin

Reputation: 126722

Update

I have noticed that you need left_column and right_column only as temporary variables.

You may prefer this

posts = %W{ A B C D E F G H I J}

indices = posts.each_index.partition(&:even?).flatten
posts = posts.values_at(*indices)

p posts

output

["A", "C", "E", "G", "I", "B", "D", "F", "H", "J"]

If you use each_with_index you can push to different arrays depending on whether the index is even or odd

posts.each_with_index do |post, i|
  (i.even? ? left_column : right_column) << post
end

Upvotes: 1

Related Questions