This is an extension to Ruby's String class. Just put this code in a file and include it. This basically takes a string and adds literals and padding to it. For example, you can format a phone number like this:
"5445556747".using('(###) ###-####', '', true)
=> (544) 555-6747
require 'strscan'
class String
def using(pattern, fill='', right=false, fixchar='#', remchar='&')
remCount = pattern.count(remchar)
raise ArgumentError.new("Too many #{remchar}") if remCount > 1
raise ArgumentError.new("#{fixchar} too long") if fixchar.length > 1
raise ArgumentError.new("#{remchar} too long") if remchar.length > 1
raise ArgumentError.new("#{fill} too long") if fill.length > 1
remaining = remCount != 0
slots = pattern.count(fixchar)
if fill.nil?
return self if self.length < slots
return self if self.length > slots and !remaining
end
source = if fill.nil? || fill.empty? then
self
elsif right then
self.rjust(slots, fill)
else
self.ljust(slots, fill)
end
if source.length > slots && !remaining then
source = right ? source[-source.length, source.length] :
source[0, source.length]
end
if !fill.nil? && fill.empty? then
if source.length < slots
keepCount = source.length
leftmost, rightmost = 0, pattern.length - 1
if right then
leftmost = (1...keepCount).inject(pattern.rindex(fixchar)) {
|leftmost, n| pattern.rindex(fixchar, leftmost - 1) }
else
rightmost = (1...keepCount).inject(pattern.index(fixchar)) {
|rightmost, n| pattern.index(fixchar, rightmost + 1) }
end
pattern = pattern[leftmost..rightmost]
slots = pattern.count(fixchar)
end
if source.length == slots then
if pattern.match("^#{Regexp.escape(remchar)}") then
pattern = pattern[pattern.index(fixchar) || 0 ... pattern.length]
elsif pattern.match("#{Regexp.escape(remchar)}$") then
pattern = pattern[0 ... (pattern.rindex(fixchar) + fixchar.length) || pattern.length]
end
end
end
remSize = source.length - slots
if remSize < 0 then remSize = 0; end
scanner = ::StringScanner.new(pattern)
sourceIndex = 0
result = ''
fixRegexp = Regexp.new(Regexp.escape(fixchar))
remRegexp = Regexp.new(Regexp.escape(remchar))
while not scanner.eos?
if scanner.scan(fixRegexp) then
result += source[sourceIndex].chr
sourceIndex += 1
elsif scanner.scan(remRegexp) then
result += source[sourceIndex, remSize]
sourceIndex += remSize
else
result += scanner.getch
end
end
result
end
end