Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to initialize a temp variable that is used in a loop

Tags:

ruby

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
like image 752
wiredin Avatar asked Jan 14 '23 11:01

wiredin


1 Answers

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).

like image 164
Zach Kemp Avatar answered Feb 11 '23 05:02

Zach Kemp