Mega Code Archive

 
Categories / Ruby / Array
 

Add a new method to Array class

class Array  def each_from_both_sides     front_index = 0     back_index = self.length-1     while front_index <= back_index       yield self[front_index]       front_index += 1       if front_index <= back_index     yield self[back_index]         back_index -= 1       end     end   end end new_array = [] [1,2,3,4,5].each_from_both_sides { |x| new_array << x } p new_array                         # => [1, 5, 2, 4, 3]