04 Jul, 2009, Runter wrote in the 1st comment:
Votes: 0
The idea here is to be able to still us the efficient center call in the core.
I've tested some pure ruby solutions and they seemed better but ended up being a wash with more lines and even slightly less efficient.
I welcome some other solutions here for certain. :)
### extend center function for strings.
class String
### redefine center to o_center
alias o_center center

def bust_color code='#' ### Change this to your code or pass it in bust_color
gsub! Regexp.new("#{code}[^0-9^#{code}^ ]"), ""
end

def center count, fill=' '
s = self.dup ### dup self
s.bust_color
s.o_center(count, fill).sub(s, self)
end
end

teststr = "jfwof #r#r#rtest #y#y#ystring"

puts teststr.center 20, '_'
1000.times do
teststr.center 20, '_'
end


1000 iterations as usual said:
% cumulative self self total
time seconds seconds calls ms/call ms/call name
17.65 0.03 0.03 1001 0.03 0.07 String#bust_color
17.65 0.06 0.03 1001 0.03 0.15 String#center
11.76 0.08 0.02 1 20.00 170.00 Integer#times
11.76 0.10 0.02 1001 0.02 0.02 String#initialize_copy
11.76 0.12 0.02 1001 0.02 0.03 Class#new
11.76 0.14 0.02 1001 0.02 0.02 String#sub
5.88 0.15 0.01 1001 0.01 0.03 Kernel.dup
5.88 0.16 0.01 1001 0.01 0.01 Regexp#initialize
5.88 0.17 0.01 1001 0.01 0.01 String#gsub!
0.0/1