I am trying to take the following number:
423523420987
And convert it to this:
4235 2342 0987
It doesn't necessarily have to be an integer either. In fact, I would prefer it to be a string.
You can use String::gsub
with a regular expression:
=> 'abcdefghijkl'.gsub(/.{4}(?=.)/, '\0 ')
'abcd efgh ijkl'
class String
def in_groups_of(n, sep=' ')
chars.each_slice(n).map(&:join).join(sep)
end
end
423523420987.to_s.in_groups_of(4) # => '4235 2342 0987'
423523420987.to_s.in_groups_of(5, '-') # => '42352-34209-87'
To expand on @Mark Byer's answer and @glenn mcdonald's comment, what do you want to do if the length of your string/number is not a multiple of 4?
'1234567890'.gsub(/.{4}(?=.)/, '\0 ')
# => "1234 5678 90"
'1234567890'.reverse.gsub(/.{4}(?=.)/, '\0 ').reverse
# => "12 3456 7890"
If you are looking for padded zeros in case you have less than 12 or more than 12 numbers this will help you out:
irb(main):002:0> 423523420987.to_s.scan(/\d{4}/).join(' ')
=> "4235 2342 0987"
irb(main):008:0> ('%d' % 423523420987).scan(/\d{4}/).join(' ')
=> "4235 2342 0987"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With