Both array[start, count].each
and array[range].each
makes a new array (losing time and memory in allocation) and the closest way I've found is iterating through indices and accessing with array[i]
(start...stop).each do |i|
value = array[i]
# do something with `value`
end
but iterating through indices, when I want values, loses Ruby-style iteration.
Is this intentional? (maybe to avoid data-race?)
I didn't make a direct PR because I don't know if should it be in Array(T)
or Indexable(T)
and which are the best method names(or overloads). eg.:
#each(*, start : Int, stop : Int)
#each(*, within : Range(Int, Int))
#each_within(range : Range(Int, Int))
What do you think?
I actually needed this a few times and it also bothered me to go back to index iteration and then accessing the array.
So yes, having something like what you propose would be really nice, it could be applied generally to any Indexable
.
I somehow believed it should be done in compile-time optimization.
In script-like languages, I assume the compiler does all clever jobs, and I stay foolish 馃槃
@chaniks even assuming a perfect optimiser the compiler wouldn't be able to optimise this without changing the behaviour of the program because duplicating then iterating has a different behaviour to simply iterating when the array is being modified from another thread.
Most helpful comment
I actually needed this a few times and it also bothered me to go back to index iteration and then accessing the array.
So yes, having something like what you propose would be really nice, it could be applied generally to any
Indexable
.