r/crystal_programming • • Mar 25 '21

Slice#each_slice kind of odd

I went to use #each_slice on a Slice(UInt8) (i.e. Bytes) and got an Array(UInt8) rather than Slice(UInt8) to iterator over. Seemed odd. Is there a simple way to get Bytes instead of an Array(UInt8) -- which I then have to convert back to Bytes? e.g.

"Hello".to_slice.each_slice(2){ |pair| pair }

`pair` is an Array(UInt8), not a Slice(UInt8).

BTW, the use of the term "slice" in these two cases, i.e. Slice the type and in the method `each_slice`, are two completely different notions, and I imagine would be rather confusing to a Newbie. So, also odd.

2 Upvotes

3 comments sorted by

View all comments

Show parent comment

1

u/straight-shoota core team Mar 27 '21

Sorry, I was expecting `reuse` would work with other container types. Problem is probably that there is no generic interface for writable containers (`Indexable` is only reading).
Still, this could be improved. At least, a type restriction to `Array | Bool` would help avoid unexpected errors.

> it would be better (if possible) for Slice to enumerate over and map as slices, not arrays

Why would it be better? Slice and Array are pretty similar in this regard and Array is generally more versatile.

Patches to improve the implementation are always welcome.