bhbrinckerhoff
11/20/2004 11:29:00 AM
Yeah the naming is a bit confusing. Probably the best way to get this
functionality to to add a method to the Array class
def new_slice(num)
outer = []
inner = nil
each_index do |i|
if i % num == 0
inner = []
outer << inner
end
inner << slice(i)
end
return outer
end
Then you can just do
[1,2,3,4,5,6].new_slice(2)#=>[[1, 2], [3, 4], [5, 6]]
[1,2,3,4,5,6].new_slice(3)#=>[[1, 2, 3], [4, 5, 6]]
[1,2,3,4,5].new_slice(2) #=>[[1, 2], [3, 4], [5]]
[1,2,3,4,5].new_slice(5) #=>[[1, 2, 3, 4, 5]]
[1,2,3,4,5].new_slice(4) #=>[[1, 2, 3, 4], [5]]
[1,2,3,4,5].new_slice(6) #=>[[1, 2, 3, 4, 5]]
It's probably not as concise or clever as your were hoping :) but
it'll do the job.
Ben
"trans. (T. Onoma)" <transami@runbox.com> wrote in message news:<200411190820.08927.transami@runbox.com>...
> Are Enumerator#each_slice and #enum_slice properly named? All they take is an
> integer which groups the enumerator's elements:
>
> [1,2,3,4,5,6].to_enum.enum_slice(2).to_a
> #=> [[1,2],[3,4],[5,6]]
>
> Yet Array#slice does nothing of the sort:
>
> [1,2,3,4,5,6].slice(2)
> #=> 3
>
> Also, how does one achieve #enum_slice functionality without Enumerator using
> only Array?
>
> T.