ruby - How to refactor this code to remove output variable? -


def peel array   output = []    while ! array.empty?     output << array.shift     mutate! array   end    output.flatten end 

i have not included mutate! method, because interested in removing output variable. mutate! call important because cannot iterate on array using each because array changing.

edit: getting array output, want. method works correctly, think there way collect array.shift values without using temp variable.

edit #2: ok, here mutate! method , test case:

def mutate! array   array.reverse! end  = (1..5).to_a peel( ).should == [ 1, 5, 2, 4, 3 ] 

it doesn't matter if peel modifies array. guess should called peel!. yes, mutate! must called after each element removed.

all reversing makes me dizzy.

def peel(array)   indices = array.size.times.map |i|     = -i if i.odd?     = i/2   end    array.values_at(*indices) # indices [0, -1, 1, -2, 2] in example end  = (1..5).to_a p peel(a) #=>[1, 5, 2, 4, 3] 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

html - Repeat image to extend header to fill screen -

javascript - Backbone.js getting target attribute -