align_columns.sf 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/ruby
  2. class Format(text, width) {
  3. method align(j) {
  4. text.map { |row|
  5. row.range.map { |i|
  6. '%-*s ' % (width[i],
  7. '%*s' % (row[i].len + (width[i]-row[i].len * j/2), row[i]));
  8. }.join("");
  9. }.join("\n") + "\n";
  10. }
  11. }
  12. func Formatter(text) {
  13. var textArr = [];
  14. var widthArr = [];
  15. text.each_line {
  16. var words = .split('$');
  17. textArr.append(words);
  18. words.each_kv { |i, word|
  19. if (i == widthArr.len) {
  20. widthArr.append(word.len);
  21. }
  22. elsif (word.len > widthArr[i]) {
  23. widthArr[i] = word.len;
  24. }
  25. }
  26. }
  27. return Format(textArr, widthArr);
  28. }
  29. enum |left, middle, right|;
  30. const text = <<'EOT';
  31. Given$a$text$file$of$many$lines,$where$fields$within$a$line$
  32. are$delineated$by$a$single$'dollar'$character,$write$a$program
  33. that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
  34. column$are$separated$by$at$least$one$space.
  35. Further,$allow$for$each$word$in$a$column$to$be$either$left$
  36. justified,$right$justified,$or$center$justified$within$its$column.
  37. EOT
  38. var f = Formatter(text);
  39. say f.align(left);
  40. say f.align(middle);
  41. say f.align(right);