开发者

Line formatting with Ruby

There is a text file containing words with 1 space between each of them. And there is also a command line entry that gives the length of line (output) wanted. Output will be words that fit into the length of the line (taken from command line).

Also the fi开发者_运维知识库rst word will be on the left side of the line and the last word will be right side of it. The spaces between each word will be same.

Any help will be appreciated thanks for replying.


A little dab of regular expression will do ya:

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"

The regular expression, broken down:

\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

The bit of Perl-esque at the end returns the matched string, or if no match, an empty string. It breaks down like this:

&&        If true (i.e., if match)
$&        matched string
||        else
''        empty string


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜