So I've got my code trying to select an object from an array of objects, and if the object isn't found, I want to create my defaults.
所以我的代码试图从一个对象数组中选择一个对象,如果找不到该对象,我想创建我的默认值。
lead_time = lead_times.select{|d| LeadTimeProfile.new unless d.day_of_week == day }
however, from what I can tell, this is not returning me the devault LeadTimeProfile.
但是,据我所知,这并没有让我失去了LeadTimeProfile。
is there a way of doing this? Or have I got it right?
有没有办法做到这一点?或者我做对了吗?
2 个解决方案
#1
3
So I've got my code trying to select an object from an array of objects, and if the object isn't found, I want to create my defaults.
所以我的代码试图从一个对象数组中选择一个对象,如果找不到该对象,我想创建我的默认值。
Take a look at Enumerable#find
看看Enumerable#find
lead_time = lead_times.find{ |d| d.day_of_week == day } || LeadTimeProfile.new
#2
0
filter your array first, and then do the construction
首先过滤你的数组,然后进行构造
lead_time = lead_times.select{|d| d.day_of_week == day}.map {|d| LeadTimeProfile.new(d)}
lead_time = lead_times.select {| d | d.day_of_week == day} .map {| d | LeadTimeProfile.new(d)}
#1
3
So I've got my code trying to select an object from an array of objects, and if the object isn't found, I want to create my defaults.
所以我的代码试图从一个对象数组中选择一个对象,如果找不到该对象,我想创建我的默认值。
Take a look at Enumerable#find
看看Enumerable#find
lead_time = lead_times.find{ |d| d.day_of_week == day } || LeadTimeProfile.new
#2
0
filter your array first, and then do the construction
首先过滤你的数组,然后进行构造
lead_time = lead_times.select{|d| d.day_of_week == day}.map {|d| LeadTimeProfile.new(d)}
lead_time = lead_times.select {| d | d.day_of_week == day} .map {| d | LeadTimeProfile.new(d)}