初始化循环中用于跟踪先前值的临时变量的最佳方法是什么?
以下是我将如何做的示例,但我觉得有一种更清洁的方式。如果之前的节目是在另一天,我只想打印节目日期
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
答案 0 :(得分:5)
我可能会使用group_by
对数据进行重组,因此它或多或少匹配所需的输出。然后你可以输出一次日期,因为它成为哈希中的键,然后是该日期的节目数组:
shows.group_by(&:date).each do |date, date_shows|
puts date
puts date_shows
end
(我使用IRB的默认行为将数组作为参数提供给puts
,其中每个元素都打印在一个新行上。如果你需要用它们做其他的事情,你可以循环遍历那个数组)。
答案 1 :(得分:2)
我可以用不同的方式写你的剪辑,但回答你的问题
初始化临时变量的最佳方法
将是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 :(得分:1)
所以你想要迭代每组两个连续的元素。试试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
答案 3 :(得分:1)
这显示了一种方法(使用简单的数组;您必须适应您的特定对象类型):
arr = [1,1,2,1,2,2,3,1]
arr.each_cons(2) do |a,b|
puts b unless b == a
end
答案 4 :(得分:0)
shows.each_cons(2) do |s1, s2|
puts s2.date unless s1.date == s2.date
puts s2.name
end
要打印第一个,您可以准备一个虚假节目dummy
,其日期为空,并使用[dummy, *shows]
代替shows
。