tags:

views:

59

answers:

3

In this question, the asker requests a solution that would insert a space every x number of characters. The answers both involve using a regular expression. How might you achieve this without a regex?

Here's what I came up with, but it's a bit of a mouthful. Any more concise solutions?

string = "12345678123456781234567812345678"
new_string = string.each_char.map.with_index {|c,i| if (i+1) % 8 == 0; "#{c} "; else c; end}.join.strip
=> "12345678 12345678 12345678 12345678"
A: 
class Array
  # This method is from
  # The Poignant Guide to Ruby:
  def /(n)
    r = []
    each_with_index do |x, i|
      r << [] if i % n == 0
      r.last << x
    end
    r
  end
end

s = '1234567890'
n = 3
join_str = ' '

(s.split('') / n).map {|x| x.join('') }.join(join_str)
#=> "123 456 789 0"
Adrian
A: 

This is slightly shorter but requires two lines:

new_string = ""
s.split(//).each_slice(8) { |a| new_string += a.join + " " }
Alex - Aotea Studios
It also uses a regular expression ;)
Gareth
+3  A: 
class String
  def in_groups_of(n)
    chars.each_slice(n).map(&:join).join(' ')
  end
end

'12345678123456781234567812345678'.in_groups_of(8)
# => '12345678 12345678 12345678 12345678'
Jörg W Mittag
Gah. Beat me to it by seconds :)
thorncp