jay
jay

Reputation: 12495

What is an elegant way to condense this loop?

I want to accomplish the following:

 def feed_items
  a = []
  taggings.each do |k| 
    a << k.feed_item 
  end

  return a
 end

How can I write this better? It's ugly to have to initialize the array to start out, and I feel like there is a much more condense way to do this. For your information, this is for an object that has_many taggings, and each tagging has a feed_item.

Upvotes: 0

Views: 108

Answers (1)

Dave Newton
Dave Newton

Reputation: 160321

I don't understand; your loop doesn't do anything, and the method returns an empty array.

Are you trying to do this?

def feed_items
  taggings.collect &:feed_item
  # Or taggings.collect { |t| t.feed_item }
end

Upvotes: 5

Related Questions