[英]get the latest version from an array in ruby
I have an array of version numbers called unique_versions that keeps on increasing : 我有一个名为unique_versions的版本号数组,它们不断增加:
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. 我需要从阵列中获取最新的(1.7.16)。 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)
版本处理已在Gem::Version
(以及其他版本)中实现,无需重新发明轮子。
string_versions.max_by{ |s| Gem::Version.new(s) } # => "1.7.16"
This seems to work 这似乎有效
unique_versions.sort_by { |version| version.split('.').map(&:to_i) }
=> ["0.0.1", "1.1.0", "1.2.0", "1.2.1", "1.6.2", "1.7.2", "1.7.4", "1.7.5", "1.7.7", "1.7.9", "1.7.12", "1.7.13", "1.7.14", "1.7.16"]
so 所以
unique_versions.max_by { |version| version.split('.').map(&:to_i) }
=> "1.7.16"
Note that you can rewrite this part 请注意,您可以重写此部分
version_array = Array.new
json_file["results"].each do |version|
version_array.push(version["version"].sub /-.*$/, '')
end
unique_versions=(version_array.uniq)
in something like 在类似的东西
unique_versions = json_file["results"].map { |version| version["version"].sub /-.*$/, '' }.uniq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.