Main Content

Clarrissa-Marybelle - too long to really fit?

Archive - Originally posted on "The Horse's Mouth" - 2015-10-23 06:55:25 - Graham Ellis

Would you christen your child Clarissa-MaryBelle? No, neither would I, but someone might - and there's a name that's so long it won't fit into boxes on forms.

When programming, there's a need to format things to line up, and in a ixed with font / plain text data file, that's done withspae pading - usinf the printf function, the % operator, or the .format method depending on your language. This week, I've been teaching Ruby and used the % operator therein.

Here's a first format - a fixed format using 10 character positions for the name:
  puts "A child called %-10s was born to them" % offspring

Of course, Clarissa-MaryBelle is going to stand out. Tthe "10" is a mimimum field width, so she won't be truncated though. But to get her all lined up, you can do better. A good solution is to search through all the names you need to output, and make up your format string using the longest that yu find.

The search:
  longest = 0
  family.each do |offspring|
    longest < offspring.length and longest = offspring.length
  end


and the print:
  puts "Child %2d called %#{longest}s was born to them" % [osn,offspring]
(which has an extra field too - the chld number - in the output)

Full example, including sample output, [here].