Array operation

For example, such an array [1, 2, 5, 3, 6, 5, 2, 1], I want to delete the repeated elements in the array, and output the remaining arrays from small to large, the result is [1,2,3,5,6], then what should I do, if you can help me answer, I would be grateful

The uniq method removes all duplicate elements and retains all unique elements in the array.

arr = [1, 2, 5, 3, 6, 5, 2, 1]
arr.uniq
[1, 2, 5, 3, 6]

The sort! method sorts the data in place.

arr = [1, 2, 5, 3, 6, 5, 2, 1]
arr.sort!
[1, 1, 2, 2, 3, 5, 5, 6]

Solution for your situation:

arr = [1, 2, 5, 3, 6, 5, 2, 1]
arr.uniq.sort!
[1, 2, 3, 5, 6]
3 Likes

Thank you for your wonderful advice. I solved the problem through your method

1 Like

For methods of Ruby core classes, refer to the official Ruby documentation …

1 Like