rubysortingnatural-sortversion-sort

Version sort (with alphas, betas, etc.) in ruby


How do I sort a list of versions in Ruby? I've seen stuff about natural sort, but this is a step beyond that.

Input is a bunch of strings like this:

input = ['10.0.0b12', '10.0.0b3', '10.0.0a2', '9.0.10', '9.0.3']

I can almost do it with the naturally gem:

require 'naturally'
Naturally.sort(input)
=> ["9.0.3", "9.0.10", "10.0.0a2", "10.0.0b12", "10.0.0b3"]    

Problem: 10.0.0b3 is sorted after 10.0.0b12; 10.0.0b3 should be first.

Anyone have a way that works? Other languages are helpful too!


Solution

  • Ruby ships with the Gem class, which knows about versions:

    ar = ['10.0.0b12', '10.0.0b3', '10.0.0a2', '9.0.10', '9.0.3']
    
    p ar.sort_by { |v| Gem::Version.new(v) }
    # => ["9.0.3", "9.0.10", "10.0.0a2", "10.0.0b3", "10.0.0b12"]