Meaning of #slice

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.

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 :slight_smile: 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.

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

Array#slice takes a starting index and the optional second arg tells
how many elements to take. in Enumerator#enum_slice, the starting
index is pointless, so I guess they just eliminated it; so all you
have left is the optional second arg, the size of the slice. Just a
guess.

Also, how does one achieve #enum_slice functionality without Enumerator using
only Array?

tmp = array_to_work_with.dup
until tmp.empty?
  do_stuff_with( tmp.slice!(0, size) )
end

hth,
Mark

···

On Fri, 19 Nov 2004 22:20:12 +0900, trans. (T. Onoma) <transami@runbox.com> wrote: