Книга: Программирование на языке Ruby

2.40. Цитирование текста

2.40. Цитирование текста

Иногда бывает необходимо напечатать длинные строки текста, задав ширину поля. Приведенный ниже код решает эту задачу, разбивая текст по границам слов и учитывая символы табуляции (но символы забоя не учитываются, а табуляция не сохраняется):

str = <<-EOF
  When in the Course of human events it becomes necessary
  for one people to dissolve the political bands which have
  connected them with another, and to assume among the powers
  of the earth the separate and equal station to which the Laws
  of Nature and of Nature's God entitle them, a decent respect
  for the opinions of mankind requires that they should declare the
  causes which impel them to the separation.
EOF
max = 20
line = 0
out = [""]
input = str.gsub(/n/, " ")
words = input.split(" ")
while input ! = ""
 word = words.shift
 break if not word
 if out[line].length + word.length > max
  out[line].squeeze!(" ")
  line += 1
  out[line] = ""
 end
 out[line] << word + " "
end
out.each {|line| puts line} # Печатает 24 очень коротких строки.

Библиотека Format решает как эту, так и много других схожих задач. Поищите ее в сети.

Оглавление книги

Оглавление статьи/книги

Генерация: 1.207. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз