New to Ruby (coming from Python) and try to experiment this exercise:
(mixed the array items by taking first, last in rotating fashion)
Expected Output to be - [1, 7, 2, 6, 3, 5, 4]. But I did not expect 'nil' at the end... The orig. array can contain even or odd size of numbers.
Can someone shed the light of this unexpected? Thanks in advance. [Updates - re-write the example from Ruby Cookbook p.162 Array ]
nums = (1..7).to_a # [1, 2, 3, 4, 5, 6, 7]
mixed = []
#middle = nums.length / 2
#index = 0
until nums.empty?
mixed << nums.shift(). #get 1st element out
mixed << nums.pop() #get last element out
#index += 1
end
print mixed # Got [1, 7, 2, 6, 3, 5, 4, nil]
shiftthe last value off you thenpop, perhaps forgetting to see if there is any data left. Put left finger at the start of the array, right at the end. When you sayshiftmove your left finger to the right; when you saypopmove your right finger to the left. See?[].pop # => nil[].shift #=> nilSo last step in your example will producenilsince you have 2 operations in one iterationirb. Just don't use the loop; create your array, and unroll the loop "by hand".