Ruby Array : sort, reverse and unique

numbers = [1, 4, 6, 7, 3, 2, 5]
=> [1, 4, 6, 7, 3, 2, 5]

Sort

numbers.sort
=> [1, 2, 3, 4, 5, 6, 7]

numbers = [1, 4, 6, 7, 3, 2, 5]
=> [1, 4, 6, 7, 3, 2, 5]
numbers.sort!
=> [1, 2, 3, 4, 5, 6, 7]

Reverse

numbers.reverse
=> [7, 6, 5, 4, 3, 2, 1]

Unique

numbers = [1, 4, 6, 7, 3, 2, 5, 1, 2]
=> [1, 4, 6, 7, 3, 2, 5, 1, 2]

numbers.uniq
=> [1, 2, 3, 4, 5, 6, 7]
numbers = [1, 4, 6, 7, 3, 2, 5]
=> [1, 4, 6, 7, 3, 2, 5]
numbers.uniq!
=> [1, 2, 3, 4, 5, 6, 7]

Note : Using Exclamation mark to make changes in original array

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Interview Question on Ruby on Rails