开发者

Rails 'returning' method - One-liner to build Array from Multiple Arrays in Ruby?

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

def questions
  results = []
  sections.each do |section|
    resul开发者_StackOverflow社区ts = 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.


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.


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


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.


Without a block in sight:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜