1

I want to sort an array to keep the years in ascending order and continue in the right sequence.

It is for a simple ruby ​​application.

Suppose my array is a = [ "Influenza - 2015", "Influenza - 2019", "Influenza - 2016", "Hepatite B", "Influenza - 2018", "Influenza - 2017"]

I want my output to be:

Hepatite B
Influenza - 2019
Influenza - 2018
Influenza - 2017
Influenza - 2016
Influenza - 2015
2
  • 1
    The shown output years are not in ascending order. Commented Sep 5, 2019 at 14:18
  • You need to edit to change “ascending” to “descending” to be consistent with the title and example. Commented Sep 5, 2019 at 14:37

3 Answers 3

1

You can sort by regex match on numeric at end of string and fallback to string if there's no regex match, then reverse it.

a = [ "Influenza - 2015", "Influenza - 2019", "Influenza - 2016", "Hepatite B", "Influenza - 2018", "Influenza - 2017"]

puts a.sort_by{|s| s[/\d+$/] || s}.reverse

will output:

Hepatite B
Influenza - 2019
Influenza - 2018
Influenza - 2017
Influenza - 2016
Influenza - 2015
Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't work correctly because it's sorting by years. Try it for this array: [ "Influenza - 2015", "Influenza - 2019", "Influenza - 2016", "Hepatite B", "Influenza - 2018", "Influenza - 2017", "A - 2019", "A - 2016", "A - 2014"]
1

Option using String#split:

"Influenza - 2015".split(' - ') #=> ["Influenza", "2015"]

So,

a.sort_by{ |e| e.split(' - ').last }.reverse
#=> ["Herpes 1", "Hepatite B", "Influenza - 2019", "Influenza - 2018", "Influenza - 2017", "Influenza - 2016", "Influenza - 2015"]

2 Comments

Are you aware that herpes was first documented as a disease (by Athenaeus of Attalia) in 1 AD?
I didn't. But I didn't have any "Herpes 1" string in my array. It popped up from nowhere while sorting! Maybe for that! :))
0
a.sort_by do |s|
  yr = s[/\d{4}\z/]
  yr.nil? ? [0], [1, -yr.to_i]
end

Sorting is done by pairwise comparisons of arrays using the method Array#<=>. See especially the third paragraph of the doc.

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.