views:

373

answers:

3

How do I convert the following to a clear one-liner in ruby?

def questions
  results = []
  sections.each do |section|
    results = results.concat(Question.find_all_by_survey_section_id(section.id))
  end
  results
end

I feel like I could use the &: (Symbol#to_proc) and returning methods in there somehow.

+2  A: 
def questions
  sections.map do |section|
    Question.find_all_by_survey_section_id(section.id)
  end.flatten
end

or

def questions
  sections.inject([]) do |all, section|
    all.concat Question.find_all_by_survey_section_id(section.id)
  end
end
Simone Carletti
+1 for `inject`
molf
A: 

You can use map or collect, like so

def questions
  sections.map{|section| Question.find_all_by_survey_section_id(section.id)}.flatten
end

However, I dont think you can use symbol to proc for this because you are not just calling a method on the collection.

nas
+2  A: 

Assuming that SurveySection has_many :questions, you can simplify this to:

sections.map(&:questions).flatten

Or if the method is defined in an ActiveRecord model, you could just declare that it has_many :questions, :through => :sections and you won't have to define the method at all.

sepp2k
thank you! that's exactly what I was looking for, makes sense now.
viatropos