のえら

技術備忘とかメモとか.間違いはつっこんでいただきたい所存.アフィリエイトはやっていません.

rubocop で ruby の数字の桁区切りをアンダースコアでできることを知った話

Use underscores(_) as decimal mark and separate every 3 digits with them.

プロジェクトに導入している rubocop で上記のメッセージが出た。
ruby では10000のような大きな数字を使うとき、人の目で見てパッと何桁かを理解できるよう、任意の箇所に _ (アンダースコア) で区切ることができる、とのこと。
rubocop 的には3桁ごとにアンダースコアを入れなさいよ、と警告しているので 100_00 も 10_000 も許容する。
※桁区切り(カンマ区切り)なので後者の方が見やすいと思われる(よく日本語にはなじまないとか言われてるけど。。)

このアンダースコアはプログラム上無視される。
以下 rails console で検証。

[1] pry(main)> number = 10_000
=> 10000
[2] pry(main)> number == 10_000
=> true
[3] pry(main)> number == 10000
=> true
[4] pry(main)> 10_000 == 10000
=> true
[5] pry(main)> 10_000.class
=> Integer
[6] pry(main)> number.class
=> Integer

rubocop のデフォルトでは5桁以上で適用
https://github.com/bbatsov/rubocop/blob/master/config/default.yml#L1076-L1078

定義は Style/NumericLiterals
https://github.com/bbatsov/rubocop/blob/master/config/enabled.yml#L784-L789

ruby style guide では以下のように記述されている。
https://github.com/bbatsov/ruby-style-guide#underscores-in-numerics

Add underscores to large numeric literals to improve their readability.


# bad - how many 0s are there?
num = 1000000

# good - much easier to parse for the human brain
num = 1_000_000