Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
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 – icy 2 days ago
add comment (requires an account with 50 reputation)

2 Answers

Do you mean slice! (http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-slice-21) as in:

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]
share|improve this answer
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) – Ashish Kumar Aug 8 at 21:46
ar.slice!(2..-1) – Rob Di Marco Aug 8 at 22:30
add comment (requires an account with 50 reputation)

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.

share|improve this answer
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.