如果.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
答案 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
代替inject
或each_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}}所有元素的数组。