0

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?

1
  • when slicing, a new object is created anyway; just test with repeated arr[0..2].object_id in irb, for example. You might as well make it readable, so I'd go with Amy Hua's arr = arr.first 3 Commented Aug 9, 2013 at 20:31

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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]

1 Comment

nice, but i want to take only starting part to remain in the array.so i can do it as arr.slice!(2,arr.length-1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.