2010-05-20 78 views
0

有一个文本文件,其中包含每个文字之间有1个空格的文字。还有一个命令行条目给出了想要的行(输出)的长度。输出将是适合该行长度的单词(从命令行获取)。使用红宝石线格式化

此外,第一个单词将位于该行的左侧,最后一个单词将位于该单词的右侧。每个单词之间的空格将相同。

任何帮助将不胜感激谢谢你的回复。

+0

这功课? – Anna 2010-05-20 14:48:09

+0

类似的东西。 – dbtek 2010-05-21 10:53:12

回答

1

正则表达式的一个小民建联会做雅:

s = "The quick brown fox jumps over the lazy dog" 

def limit_length(s, limit) 
    s =~ /\A.{0,#{limit}}(?=\Z|)/ && $& || '' 
end 

p limit_length(s, 2) # => "" 
p limit_length(s, 3) # => "The" 
p limit_length(s, 42) # => "The quick brown fox jumps over the lazy" 
p limit_length(s, 43) # => "The quick brown fox jumps over the lazy dog" 

正则表达式,细分:

\A    From the beginning of the string 
.{0,#{limit}}  Match up to *limit* characters 
(?=\Z|)   Followed by the end of the string or a blank 

Perl的去年秋季的结尾处的位返回匹配字符串,或者如果不匹配,则为空字符串。它分解如下:

&&  If true (i.e., if match) 
$&  matched string 
||  else 
''  empty string 
1
File.open('input.txt').each do |l| 
    length_so_far = 0 
    puts l.split(' ').select{|w| (length_so_far += w.length) < max_length}.join(' ') 
end