views:

60

answers:

2

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 first 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: 
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
Jakub Hampl
A: 

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
Wayne Conrad