LoginSignup
4
0

More than 5 years have passed since last update.

出来らあっ!PureRubyで正規表現を使わずに文字列へ3桁毎にカンマ食わせられるっていったんだよ!!

Last updated at Posted at 2018-12-19

え??PureRubyで正規表現を使わずに文字列へ3桁毎にカンマを??

RUBY_VERSION
=> "2.5.3"
p 1234567.to_s.reverse.chars.each_slice(3).map(&:join).join(',').reverse
# => "1,234,567"
p 1234567.to_s.chars.reverse_each.each_slice(3).map(&:join).join(',').reverse
# => "1,234,567"
class String
  def recursive
    return self if self.size <= 3
    self[0..-4].recursive + ',' + self[-3, 3]
  end
end
1234567.to_s.recursive
# => "1,234,567"

なんの変哲もなくてすまん

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