meaning of #slice

T

trans. (T. Onoma)

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.
 
B

Ben

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
 
M

Mark Hubbart

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,430
Latest member
7dog123

Latest Threads

Top