Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 初始化循环中使用的临时变量的最佳方法_Ruby - Fatal编程技术网

Ruby 初始化循环中使用的临时变量的最佳方法

Ruby 初始化循环中使用的临时变量的最佳方法,ruby,Ruby,初始化循环中用于跟踪上一个值的临时变量的最佳方法是什么 这里是我将如何做的例子,但我觉得有一个更干净的方法。我只想在前一场演出在不同的日子时打印演出日期 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 我可能会使用group\u by重新构造数据

初始化循环中用于跟踪上一个值的临时变量的最佳方法是什么

这里是我将如何做的例子,但我觉得有一个更干净的方法。我只想在前一场演出在不同的日子时打印演出日期

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

我可能会使用
group\u by
重新构造数据,使其或多或少与所需的输出相匹配。然后可以输出一次日期,因为它成为散列中的键,然后是该日期的显示数组:

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

(我使用IRB的默认行为将数组作为参数提供给
puts
,其中每个元素都打印在新行上。如果需要对数组执行其他操作,可以循环该数组)。

因此,您希望迭代每组两个连续元素。试一试

这显示了一种方法(使用简单数组;您必须适应特定的对象类型):


要打印第一个,您可以准备一个日期为空的虚拟节目
dummy
,并使用
[dummy,*shows]
而不是
shows

我可以用不同的方式编写剪贴,但回答您的问题

初始化临时变量的最佳方法

将是
每个带有\u对象的\u

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

如果前两个日期不同(且第一个不是“”),OP的代码将打印两个日期。这个版本只打印第二个。这太完美了!谢谢,现在我明白了为什么人们真的喜欢ruby了。你能告诉我(&:date)组中的“&”是什么吗?@wiredin这是ruby的缩写。用简单的英语,它在
shows
集合中的每个项目上调用
date
方法。嗨,这是我不知道我能做的,谢谢!这也可能是一个很好的解决方案。每个选项似乎都是一个非常有用的方法。我想我的问题问错了,这是一个初始化变量的好方法,但我也在寻找不需要新变量的答案。谢谢
arr = [1,1,2,1,2,2,3,1]
arr.each_cons(2) do |a,b|
  puts b unless b == a
end
shows.each_cons(2) do |s1, s2|
  puts s2.date unless s1.date == s2.date
  puts s2.name
end
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