1
1

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 5 years have passed since last update.

semverを数値に変換する

Last updated at Posted at 2017-03-27

モバイルアプリで利用するWeb APIで、アプリのバージョンに応じて処理を分岐したい場合があるが、
私の場合モバイルアプリでSemantic Versioning 2.0.0を採用することが多いため、
semverで規定される1.0.0のような形式のバージョン表記は通常文字列で扱うため、そのままでは数値として大小の比較をすることができない。
そこで、これを数値に変換し、数値としての大きさで比較できるようにする。

Rubyで書くとこんな感じだろうか。
'1.2.3'.split('.').map.with_index {|n, i| n.to_i * (1000 ** (2 - i)) }.inject(:+) # => 1002003
'1.2.3'.gsub(/\.(\d+)/){ "%03d" % $1 }.to_i #=> 1002003

このコードの場合MAJOR, MINOR, PATCHそれぞれが3桁以内で正しく動作するが、1000の部分を書き換えればもっと大きな桁にも対応できる。

1
1
3

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?