2010-07-02 2 views
1

this 질문에서 asker는 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

GAH를. 초 만에 나를 이길 :) – thorncp

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

관련 문제