LoginSignup
31
28

More than 5 years have passed since last update.

整数に3桁区切りカンマを仕込む備忘録

Last updated at Posted at 2014-08-19

はじめに

Rubyで3桁区切の金額でカンマを差し込むやり方のメモ。よくあるやつですみません。
ちょっと調べたらたくさん方法は出てきたので、整数で使えるようにIntegerのクラスに突っ込んどく。

jpy_comma.rb

class Integer
  def jpy_comma
    self.to_s.gsub(/(\d)(?=(\d{3})+(?!\d))/, '\1,')
  end
end

クラスのメソッドにあるか確認

念の為に使えるメソッドに入っているか確認してみた。IntegerだとFixnumでもOKなんですね。
Integer < Numeric < Comparable < Object < Kernel < BasicObject というクラスの継承なようで、
Integerは配下にFixnumとBignumがあるみたいです。

pry.rb
numeric = 123456
p numeric.class 
=> Fixnum
p numeric.methods
=> :jpy_comma # いっぱいあったので該当部分だけ

使ってみた

問題なさそう。

pry.rb
p numeric.jpy_comma
=> "123,456"

# もっと大きい数字
numeric = 12485456309235
p numeric.jpy_comma
=> "12,485,456,309,235"

念のため小数点を確認

きっとエラーが出てくれるはず

pry.rb
b = 13754.4566
=> 13754.4566
b.jpy_comma
NoMethodError: undefined method `jpy_comma' for 13754.4566:Float

よいよい。

31
28
7

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
31
28