Scooby Scooby - 27 days ago 5
Ruby Question

get the latest version from an array in ruby

I have an array of version numbers called unique_versions that keeps on increasing :

1.7.16
1.7.14
1.7.13
1.7.12
1.7.9
1.7.7
1.7.5
1.7.4
1.7.2
1.6.2
1.2.1
1.2.0
1.1.0
0.0.1


and I need to get the latest(1.7.16) from the array. What the most elegant ruby way of doing it ? I get this array by the following code :

require "json"
require "open-uri"
require 'openssl'

string_object = open("https://xxx", :http_basic_authentication=>["xxx"], :ssl_verify_mode=>OpenSSL::SSL::VERIFY_NONE)
json_file = JSON.parse(string_object.read)
version_array = Array.new
json_file["results"].each do |version|
version_array.push(version["version"].sub /-.*$/, '')
end
unique_versions=(version_array.uniq)

Answer

Version handling is already implemented in Gem::Version (and maybe others), no need to reinvent the wheel.

string_versions.max_by{ |s| Gem::Version.new(s) } # => "1.7.16"