0
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.

[ruby]文字列の連番

Last updated at Posted at 2017-07-04

参考:知って得する!55のRubyのトリビアな記法

succ(or next)を使う

与えられた文字列の規則に沿って、文字列を変えていってくれます。

col = '@'
60.times.map { col = col.succ }
# => ["A", "B", "C", "D", "E", "F", "G", "H", "I", 
# "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", 
# "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC",
# "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", 
# "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", #"AT",
# "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", 
# "BC", "BD", "BE", "BF", "BG", "BH"]

数と文字が混ざっていても次の文字列を出力してくれます。

"abc123".succ
# => abc124

Rangeクラスを使う

succと比べて、
末尾を決めてあげる必要はありますが、
Rangeでも同じような処理をできます。

[*"a".."d"]
# => ["a", "b", "c", "d"]

先頭と末尾で連続性が保てるものなら、
"a1"~"zz1"のようなものでも出力できます。

[*"a1".."zz1"]
# =>
# ~省略~  
# "ap2",
# "ap3",
# "ap4",
# "ap5",
# "ap6",
# "ap7",
# "ap8",
# "ap9",
# "aq0",
# ~省略~

しかし、連続性がないものの場合は[]が帰ってきます。

[*"a".."1"]
# => []
0
1
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
0
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?