0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

#Ruby で バージョン番号 ( major / minor / patch ) の配列を並び替えてみる ( sort version numbers array )

Last updated at Posted at 2020-04-23

文字列で並び替えるとうまくいかないので、ゼロ埋めして並び替える

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オープンチャットもご利用ください。

Twitter

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?