所以我的代码试图从对象数组中选择一个对象,如果找不到该对象,我想创建我的默认值。
lead_time = lead_times.select{|d| LeadTimeProfile.new unless d.day_of_week == day }
但是,据我所知,这并没有返回给我 devault LeadTimeProfile。
有没有办法做到这一点?还是我做对了?
所以我的代码试图从对象数组中选择一个对象,如果找不到该对象,我想创建我的默认值。
lead_time = lead_times.find{ |d| d.day_of_week == day } || LeadTimeProfile.new
首先过滤您的数组,然后进行构造
前导时间 = 前导时间。选择{|d| d.day_of_week == 天}.map {|d| LeadTimeProfile.new(d)}
Here is another way to get the same results as what Kyle posted. There is no difference between this and using a or gate other than maybe making chaining method calls a bit cleaner.
day = 2
lead_times.find(-> { LeadTimeProfile.new }) { |p|
p.day_of_week == day
}.day_of_week
将 lambda 作为参数传递也可以。
lead_time = lead_times.find(lambda { LeadTimeProfile.new } ){ |d| d.day_of_week == day }