The following works in Ruby for commafication (adding ,
to a number, so 12345
becomes 12,345
)
def r(s)
s.gsub(/(?<=\d)(?=(\d\d\d)+\b)/, ",")
end
s = ""
1.upto(20) do |i|
s += (i % 10).to_s
puts r(s)
end
But I wonder why the variations r2
and r3
won't work?
def r2(s)
s.gsub(/(?<=\d)(?=(\d\d\d)+)\b/, ",")
end
def r3(s)
s.gsub(/(?<=\d)(?=\d\d\d)+\b/, ",")
end
Nothing is modified at all, and I would think that 1234
does match (?<=\d)(?=(\d\d\d)+)\b
so it is a bit strange. (I tried it using Perl as well, so it is not peculiar to Ruby).
Update: The following is the output for r
, while for r2
and r3
, no ,
is added at all:
1
12
123
1,234
12,345
123,456
1,234,567
12,345,678
123,456,789
1,234,567,890
12,345,678,901
123,456,789,012
1,234,567,890,123
12,345,678,901,234
123,456,789,012,345
1,234,567,890,123,456
12,345,678,901,234,567
123,456,789,012,345,678
1,234,567,890,123,456,789
12,345,678,901,234,567,890