Ruby Q & A

 

How to sort an array in Ruby?

In Ruby, you can sort an array in various ways, depending on your specific requirements. The primary method for sorting arrays is using the `.sort` method, which returns a new array with the elements sorted in ascending order. Here’s how you can use it:

```ruby

numbers = [5, 2, 8, 1, 9]

sorted_numbers = numbers.sort

```

After running this code, the `sorted_numbers` array will contain `[1, 2, 5, 8, 9]`, which is the sorted version of the `numbers` array.

 

If you need to sort the array in descending order, you can use the `.reverse` method to reverse the sorted array:

```ruby

numbers = [5, 2, 8, 1, 9]

sorted_numbers_descending = numbers.sort.reverse

```

Now, `sorted_numbers_descending` will be `[9, 8, 5, 2, 1]`.

 

Ruby’s `.sort` method is quite versatile and can handle arrays of various data types. However, if you need more control over the sorting process, you can use the `.sort_by` method with a block to specify a custom sorting criteria. For example, to sort an array of strings by their length in descending order:

```ruby

words = ["apple", "banana", "kiwi", "grape"]

sorted_words_by_length = words.sort_by { |word| -word.length }

```

In this case, `sorted_words_by_length` will contain `[“banana”, “apple”, “kiwi”, “grape”]`, sorted by length in descending order.

Sorting arrays is a common operation in programming, and Ruby provides a variety of methods and options to make it flexible and convenient for different scenarios.

Previously at
Flag Argentina
Chile
time icon
GMT-3
Experienced software professional with a strong focus on Ruby. Over 10 years in software development, including B2B SaaS platforms and geolocation-based apps.