The best way to initialize a temporary variable that is used in a loop

What is the best way to initialize the temp variable that is used in the loop to track the previous value?

Here is an example of how I will do this, but I feel that there is a cleaner way. I only want to print the date of the show 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 
+4
source share
5 answers

I would probably restructure the data with group_by so that it more or less matches the desired result. Then you can print the date once since it becomes the key in the hash, and then an array of impressions for that date:

 shows.group_by(&:date).each do |date, date_shows| puts date puts date_shows end 

(I use the default IRB behavior to pass arrays as arguments to puts , where each element is printed on a new line. You can skip this array if you need to do something with them). A.

+5
source

I could write your cut off in a different way, but answering your question

best way to initialize a temporary variable

will 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 
+2
source

So, you want to iterate through each group of two consecutive elements. Try Listing # 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 
+1
source

This shows one approach (using a simple array, you have to adapt to your specific type of object):

 arr = [1,1,2,1,2,2,3,1] arr.each_cons(2) do |a,b| puts b unless b == a end 
+1
source
 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 dummy show whose date is empty and use [dummy, *shows] instead of shows .

0
source

Source: https://habr.com/ru/post/1479079/


All Articles