开发者

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

I am trying to tak开发者_StackOverflowe 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"


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

Modulus in Ruby

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜