dbtek
dbtek

Reputation: 928

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 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.

Upvotes: 0

Views: 355

Answers (2)

Wayne Conrad
Wayne Conrad

Reputation: 108199

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

Upvotes: 1

Jakub Hampl
Jakub Hampl

Reputation: 40573

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

Upvotes: 1

Related Questions