분할

2013-03-22 2 views
1

내 코드는 내가 매우 큰 문자열과 같은 큰 문자열이 있으면 내가 원하기 때문에 다음이 프로세스가 이러한 유형의 결과에 6.50 초 을분할

str = "Early in his first term in office, Obama signed into law economic stimulus legislation in response" 
arr= str.split(" ") 
set_element= arr.each_cons(2).to_a 
sub_str = set_element.map {|i| i.join(' ')} 

여기에 효율적인 방법으로 부분에 캐릭터

sub_str= ["Early in", "in his", "his first", "first term", "term in", "in office,", "office, Obama", "Obama signed", "signed into", "into law", "law economic", "economic stimulus", "stimulus legislation", "legislation in", "in response"] 
은 가능한 임의 효율적인 방법과 다른 방법

답변

7

스플릿 대신 스캔을 사용하면 단어 쌍을 직접 얻을 수 있습니다.

s.scan(/\S+(?:\s+\S+)?/) 

EDIT : 비교적 효율적이라는 것을 확신하기 위해 나는 a little micro-benchmark을 만들었습니다. 현재까지 표시된 답변의 결과는 다음과 같습니다.

ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-linux] 
10 times on string of size 2284879 
       user  system  total  real 
original  4.180000 0.070000 4.250000 ( 4.272856) 
sergio  2.090000 0.000000 2.090000 ( 2.102469) 
dbenhur  1.050000 0.000000 1.050000 ( 1.042167) 
+0

끝내 주셔서 감사합니다. –

1
set_element = arr.each_cons(2).to_a 

라인이 위를 생성인가 당신이 필요하지 않는 임시 물건의 톤. 시도해보십시오. 더 빨라야합니다.

str = "Early in his first term in office, Obama signed into law economic stimulus legislation in response" 
arr = str.split(" ") 
sub_str = arr.each_with_object([]).with_index do |(el, memo), idx| 
    if idx % 2 == 0 
    memo << el 
    else 
    memo.last << ' ' << el 
    end 

end 

sub_str # => ["Early in", "his first", "term in", "office, Obama", "signed into", "law economic", "stimulus legislation", "in response"] 
0

시도해 볼 수 있습니다. 한 단계 적게 :)

arr= str.scan(/\S+/) 
s = [] 
arr.each_with_index { |x, i| s << (x + " " + arr[i + 1]) if arr[i+1] }