Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.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 如何在2d数组循环中创建计数器变量?_Ruby - Fatal编程技术网

Ruby 如何在2d数组循环中创建计数器变量?

Ruby 如何在2d数组循环中创建计数器变量?,ruby,Ruby,所以我有一个数组 arr = [[2,3], [4,7] [2,9]] 想把计数器放在我的循环里吗 for x, y in arr do counter = 0 counter += 1 p counter end 它打印1,因为我用0初始化了计数器,它一直这样做。是否有任何方法可以跟踪我的循环运行了多少次?我不想在循环外部创建临时变量试试这个 arr.each_with_index do |(x, y), i| # you have your x, your y and t

所以我有一个
数组

arr = [[2,3], [4,7] [2,9]]
想把计数器放在我的循环里吗

for x, y in arr do
  counter = 0
  counter += 1
  p counter
end
它打印1,因为我用0初始化了计数器,它一直这样做。是否有任何方法可以跟踪我的循环运行了多少次?我不想在循环外部创建临时变量

试试这个

arr.each_with_index do |(x, y), i| 
 # you have your x, your y and the index in i
end

如果你想要一个基于1的计数器,每个计数器都有
。\u索引(1)
(注意
,这是两种方法)我认为一个注释就足够了,但是如果你愿意,可以随意添加:-)