2010-07-02 14 views
1

this問題,提問者請求將插入空格字符的每x數量的解決方案。答案都涉及使用正則表達式。如果沒有正則表達式,你會怎麼做到這一點?插入這是每一個X字符數沒有正則表達式

這就是我想出了,但它是一個有點拗口。更簡潔的解決方案?

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" 

回答

3
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' 
+0

爾加。打我幾秒鐘:) – thorncp 2010-07-02 21:45:22

0
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" 
-1

這是稍短,但需要兩行:

new_string = "" 
s.split(//).each_slice(8) { |a| new_string += a.join + " " } 
+0

它還使用一個正則表達式;) – Gareth 2010-07-02 21:12:12

相關問題