Syler Ruby
Syler Ruby

Reputation: 57

Ruby Array Delete at

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?

Upvotes: 3

Views: 3636

Answers (3)

knrz
knrz

Reputation: 1811

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.

Upvotes: 3

Ed Swangren
Ed Swangren

Reputation: 124642

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.

Upvotes: 2

Ward Muylaert
Ward Muylaert

Reputation: 555

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.

Upvotes: 1

Related Questions