LoginSignup
17
16

More than 5 years have passed since last update.

Rubyで前ゼロパディングされた文字列'01'をインクリメントして'02'にする

Posted at

"01" という入力値をインクリメントした "02" という文字列を出したいといったケースがよくあります。

冗長な例

num = "01".to_i # => 1
num_str = num.to_s # => "1"
"0" * (2 - num_str.length) + num.succ.to_s

Rubyに慣れてくると String#% を知って、こういうコードを書いたりします。

"%02d" % "01".to_i.succ

ところがどっこい、succは元々デキる子でStringクラスにも存在するのでした。

> "01".succ #=> "02"

String#% を使う方が可読性高い気もしますが、 succ メソッドの方がメソッドチェーン書きやすそうです。

17
16
0

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
17
16