Here is a method that emulates what you were trying to do which generates and array of arrays except I made mine an extension function that you would call like myArray.toSlicedArray(5):
inline fun <T> Array<T>.toSlicedArray(slice: Int)
= Array((size + slice - 1) / slice)
{ copyOfRange(it * slice, Math.min(size, (it + 1) * slice)) }
But that isn’t exactly emulating Ruby’s each slice and isn’t the best way to go.
In Kotlin what you probably want is something that returns a Sequence<Array<T>>
:
fun <T> Array<T>.sliceBy(slice:Int)
= Sequence { object : Iterator<Array<T>>
{
var index = 0
override fun hasNext() = index < size
override fun next(): Array<T>
{
val start = index;
index = Math.max(size, index + slice)
return copyOfRange(start, index)
}
}
}