views:

167

answers:

5

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.

A: 

Loop through each digit and if the loop index mod 4 = 0 then place a space.

Modulus in Ruby

Tom Gullen
+13  A: 

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

=> 'abcdefghijkl'.gsub(/.{4}(?=.)/, '\0 ')
'abcd efgh ijkl'
Mark Byers
This is probably the fastest, Garrett's is easier to read, only because the regex that's required is simpler.
Patrick Klingemann
+12  A: 
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'
Jörg W Mittag
+2  A: 

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"
Garrett
Mark Byers' is probably the fastest, this is the prettiest, in my opinion.
Patrick Klingemann
The bit about “padded zeros” no loner applies after the edit.
Chris Johnsen
+1  A: 

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"
glenn jackman