Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create spaces between every four integers in Ruby?

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.

like image 502
Trip Avatar asked Jun 16 '10 12:06

Trip


4 Answers

You can use String::gsub with a regular expression:

=> 'abcdefghijkl'.gsub(/.{4}(?=.)/, '\0 ')
'abcd efgh ijkl'
like image 149
Mark Byers Avatar answered Nov 04 '22 14:11

Mark Byers


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'
like image 22
Jörg W Mittag Avatar answered Nov 04 '22 12:11

Jörg W Mittag


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"
like image 33
glenn jackman Avatar answered Nov 04 '22 13:11

glenn jackman


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"
like image 40
Garrett Avatar answered Nov 04 '22 14:11

Garrett