What is the best way to initialize a temp variable that is used in a loop to keep track of a previous value?
Here is the example of how I would do it but I feel there is a cleaner way. I only want to print the show date if the previous show was on a different day
temp_show_date = ""
shows.each do |show|
if temp_show_date != show.date
puts show.date
end
puts show.name
temp_show_date = show.date
end
I would probably restructure the data using group_by
so it more or less matches the desired output. Then you can output the date once, as it becomes the key in a hash, followed by the array of shows for that date:
shows.group_by(&:date).each do |date, date_shows|
puts date
puts date_shows
end
(I'm using IRB's default behavior for supplying arrays as arguments to puts
, wherein each element is printed on a new line. You can loop through that array if you need to do something else with them).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With