Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use default value if item not found in array

Tags:

select

ruby

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.

is there a way of doing this? Or have I got it right?

like image 837
pedalpete Avatar asked Dec 01 '25 03:12

pedalpete


2 Answers

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

lead_time = lead_times.find{ |d| d.day_of_week == day } || LeadTimeProfile.new
like image 162
Kyle Avatar answered Dec 02 '25 18:12

Kyle


Passing a lambda as a parameter also works.

lead_time = lead_times.find(lambda { LeadTimeProfile.new } ){ |d| d.day_of_week == day }
like image 23
Diego Plentz Avatar answered Dec 02 '25 18:12

Diego Plentz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!