本文介绍了当用[..](切片)方法引用数组时,Ruby是否创建副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在数组的一个切片上循环。我基本上有两个主要选择。

I want to loop on a slice of an array. I have basically two main options.

ar.each_with_index{|e,i|
   next if i < start_ind
   break if i > end_ind
   foo(e)
   #maybe more code...
}

另一个我认为更优雅的选择是运行:

Another option, which I think is more elegant, would be to run:

ar[start_ind..end_ind].each{|e|
   foo(e)
   #maybe more code...
}

我担心的是Ruby可能在后台创建一个巨大的数组并进行大量内存分配。还是有某种更智能的玩法不会创建副本?

My concern is Ruby potentially creating a huge array under the hood and doing a lot of memory allocation. Or is there something "smarter" at play that does not create a copy?

推荐答案

您可以执行一个索引值循环。 ..不如第二种解决方案那么优雅,但经济。

You could do a loop of index values... not as elegant as your second solution but economical.

(start_ind..end_ind).each do |index|
  foo(ar[index])
  # maybe more code
end

这篇关于当用[..](切片)方法引用数组时,Ruby是否创建副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 14:01