Add a new method to Array class

2019-06-19 20:04栏目:技术创新
TAG:

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]

版权声明:本文由新浦京娱乐站_新浦京娱乐场官网_新浦京娱乐发布于技术创新,转载请注明出处:Add a new method to Array class