1

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.

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

0

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.

Comments

0

Without a block in sight:

def questions
  sections.map(&:id).flat_map(&Question.method(:find_all_by_survey_section_id))
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.