文字列で並び替えるとうまくいかないので、ゼロ埋めして並び替える
versions = ["1.0.10", "1.0.9", "2.0.0", "1.0.1"]
# NG
versions.sort
# unexpected order
# => ["1.0.1", "1.0.10", "1.0.9", "2.0.0"]
converted_versions =
versions.map do |version|
major, minor, patch = version.split(".")
{
version: version,
version_integer: format("%02d%02d%02d", major, minor, patch).to_i
}
end
converted_versions.sort_by { |version| version[:version_integer] }
# => [{:version=>"1.0.1", :version_integer=>10001},
# {:version=>"1.0.9", :version_integer=>10009},
# {:version=>"1.0.10", :version_integer=>10010},
# {:version=>"2.0.0", :version_integer=>20000}]
# OK
converted_versions.sort_by { |version| version[:version_integer] }.map { |version| version[:version] }
# => ["1.0.1", "1.0.9", "1.0.10", "2.0.0"]
# OK
converted_versions.sort_by { |version| version[:version_integer] }.map { |version| version[:version] }.reverse
# => ["2.0.0", "1.0.10", "1.0.9", "1.0.1"]
Original by Github issue
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。