Thursday, 8 August 2013

Slicing array in Ruby

Slicing array in Ruby

for slicing an array, we can use
2.0.0p247 :021 > arr = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
2.0.0p247 :022 > arr.each_slice(3).to_a
=> [[1, 2, 3], [4, 5]]
2.0.0p247 :034 > arr # does not change array
=> [1, 2, 3, 4, 5]
i want to take only first part of sliced array, so i did it in the
following way
2.0.0p247 :029 > arr = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
2.0.0p247 :030 > arr[0..2]
=> [1, 2, 3]
2.0.0p247 :031 > arr # does not change array
=> [1, 2, 3, 4, 5]
but it return a new array, and i want to do it in such a way that i can
take a part of array in the same array without creating a new array As in
Ruby there are some methods of changing same array by putting a '!' sign
as - sort!,reject! etc
Is there any method of doing this?

No comments:

Post a Comment