3

In the irb prompt:

array = [1,2,3,4,5]
array << 0
array.sort
[0,1,2,3,4,5]

I fully understand the above, but when I do this:

array.delete_at(2)

it deletes 3 in the array. If the first is considered 1, why the number 3 was removed instead of number 1?

3
  • are you sure that 3 was removed? it had to remove 2 instead of 1 Commented Jan 18, 2014 at 9:51
  • Hi. Let me restate: it deletes the number 3 in the array. So yes, the number 3 was removed. If I types: array.sort, it gives: [0,1,2,4,5] Commented Jan 18, 2014 at 9:53
  • You want sort! rather than sort. Commented Jan 18, 2014 at 9:59

3 Answers 3

3

Because array.sort doesn't save the sorted array, it just returns it. This means that when you call array.delete_at(2), your array is still [1,2,3,4,5,0]. What you want to call is array.sort!, which sorts and modifies your original array to become [0,1,2,3,4,5] and puts 2 where you expect to find it.

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

1 Comment

Thanks guys! The above answer is the same as below so the first one is clear. It is ashamed that the lynda program says nothing about "array.sort!"
2

array,sort returns a new array, it does not modify the original. If you want the mutating version then you use array.sort!. Otherwise, you would write:

array = array.sort

But, in this case, you're better off with simply:

array.sort!

Also...

If the first is considered 1, why the number 3 was removed instead of number 1?

Arrays in Ruby are zero-indexed, i.e., the first index is 0. Index 2 (in your sorted array which includes 0) would be 2, not 1.

Comments

1

array.sort doesn't change your array. So when running delete_at(2), your array still is [1,2,3,4,5,0]. To sort and "save" your array, use sort! instead.

Comments

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.