Reputation: 269
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
Upvotes: 4
Views: 368
Reputation: 168199
shows.each_cons(2) do |s1, s2|
puts s2.date unless s1.date == s2.date
puts s2.name
end
To print the first one, you can prepare a dummy show dummy
, whose date is empty, and use [dummy, *shows]
instead of shows
.
Upvotes: 0
Reputation: 20116
I could write your snipped differently, but answering your question
best way to initialize a temp variable
would be the each_with_object
shows.each_with_object("") do |temp_show_date, show|
if temp_show_date != show.date
puts show.date
end
puts show.name
temp_show_date = show.date
end
Upvotes: 2
Reputation: 535566
This shows one approach (using a simple array; you will have to adapt to your particular object type):
arr = [1,1,2,1,2,2,3,1]
arr.each_cons(2) do |a,b|
puts b unless b == a
end
Upvotes: 1
Reputation: 12181
So you want to iterate of each group of two consecutive elements. Try Enumerable#each_cons
shows.each_cons(2) do |first_show, second_show|
if first_show.date != second_show.date
puts "these two aren't on the same day!"
end
end
Upvotes: 1
Reputation: 11904
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).
Upvotes: 5