Ashish Kumar
Ashish Kumar

Reputation: 15

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?

Upvotes: 0

Views: 1652

Answers (2)

Rob Di Marco
Rob Di Marco

Reputation: 44942

Do you mean slice! as found in the ruby docs?:

1.9.3p392 :001 >     ar = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
1.9.3p392 :002 >     ar.slice!(0,2)
=> [1, 2]
1.9.3p392 :003 > ar
=> [3, 4, 5]

Upvotes: 2

Amy.js
Amy.js

Reputation: 536

Given

array = [1,2,3,4,5]

To return array=[1,2,3], you can:

  • Slice! off the last half, so you return the first half.

    array.slice!(3..5)
    
  • Return the first three elements and assign it to the variable.

    array = array.first 3
    

    Or

    array = array[0..2]
    

...Or use a number of other array methods.

Upvotes: 5

Related Questions