t56k
t56k

Reputation: 6981

Rails: changing repetition into loops

I'm trying to reduce repetition in my code. I have in several places this code (or variants thereof):

@articles1 = Article.all_articles(1).reverse
@articles2 = Article.all_articles(2).reverse
@articles3 = Article.all_articles(3).reverse

Is a way to change it to something like:

3.times do |i|
  @articles[i+1] = Article.all_articles(i+1).reverse
end

Cheers!

Upvotes: 0

Views: 35

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

How about:

@articles = (1..3).to_a.map { |i| Article.all_articles(i).reverse }

Upvotes: 1

Related Questions