如果为零,collection.inject([]){...}可以返回[](空)吗?

时间:2018-01-02 15:32:07

标签: ruby-on-rails ruby

如果.where()查询没有结果,则以下方法返回一个空数组。如何通过inject([]){ |memo, value| memo << value }实现这一目标?默认情况下,如果找不到inject([])查询的结果,则nil会返回.where()

def jobs_it_can_be_contacted_for
 jobs = []
 user_jobs.where("user_jobs.user_job_type IN (?)", ['job', 'represent']).each do |user_job|
  jobs << user_job.job unless user_job.job == Job.unknown
 end
 jobs
end

2 个答案:

答案 0 :(得分:3)

这不应该使用 var dataset = { hddrives: [total - value, value], }; var width = 460, height = 300, radius = Math.min(width, height) / 2; var color = d3.scale.ordinal() .range([secondColor, mainColor]); var pie = d3.layout.pie() .sort(null); var arc = d3.svg.arc() .innerRadius(radius - 100) .outerRadius(radius - 70); var svg = d3.select(divName).append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); //Draw the Circle svg.append("circle") .attr("cx", 0) .attr("cy", 0) .attr("r", 65) .attr("fill", "#F6FBF3"); var path = svg.selectAll("path") .data(pie(dataset.hddrives)) .enter().append("path") .attr("class", "arc") .attr("fill", function (d, i) { return color(i); }) .attr("d", arc); svg.append("text") .attr("dy", "0em") .style("text-anchor", "middle") .attr("class", "inside") .attr("font-size", "30px") .text(function (d) { return value; }); svg.append("text") .attr("dy", "1.5em") .style("text-anchor", "middle") .attr("class", "data") .text(function (d) { return nomeGtin; }); } 实现,此类任务有Enumerable#each_with_object

inject

FWIW,Enumerable#inject实施:

user_jobs.
    where("user_jobs.user_job_type IN (?)", ['job', 'represent']).
    each_with_object([]) do |user_job, jobs|
  jobs << user_job.job unless user_job.job == Job.unknown
end

最简洁的一个(归功于@Stefan):

user_jobs.
    where("user_jobs.user_job_type IN (?)", ['job', 'represent']).
    inject([]) do |jobs, user_job|
  user_job.job == Job.unknown ? jobs : jobs << user_job.job
end

最后一行也可能被重写为:

user_jobs.
    where("user_jobs.user_job_type IN (?)", ['job', 'represent']).
    map(&:job).
    reject { |job| job == Job.unknown }

答案 1 :(得分:0)

更简单的选择是使用Enumerable#reject代替injecteach_with_object。该方法适用于所有阵列以及活动记录关系。

通过它,您可以将代码简化为

def jobs_it_can_be_contacted_for
  user_jobs
    .where("user_jobs.user_job_type IN (?)", ['job', 'represent'])
    .map(&:job)
    .reject { |job| job == Job.unknown }
end

引用reject方法的文档:

  

返回给定enum返回block的{​​{1}}所有元素的数组。