Untuk perilaku yang sama persis dengan PHP trim
, metode paling sederhana adalah dengan menggunakan String#strip
metode, seperti:
string = " Many have tried; many have failed! "
puts "Original [#{string}]:#{string.length}"
new_string = string.strip
puts "Updated [#{new_string}]:#{new_string.length}"
Ruby juga memiliki versi edit-di-tempat, juga disebut String.strip!
(perhatikan trailing '!'). Ini tidak memerlukan pembuatan salinan string, dan dapat secara signifikan lebih cepat untuk beberapa penggunaan:
string = " Many have tried; many have failed! "
puts "Original [#{string}]:#{string.length}"
string.strip!
puts "Updated [#{string}]:#{string.length}"
Kedua versi menghasilkan output ini:
Original [ Many have tried; many have failed! ]:40
Updated [Many have tried; many have failed!]:34
Saya membuat tolok ukur untuk menguji kinerja beberapa penggunaan dasar strip
dan strip!
, serta beberapa alternatif. Tesnya adalah ini:
require 'benchmark'
string = 'asdfghjkl'
Times = 25_000
a = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
b = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
c = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
d = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
puts RUBY_DESCRIPTION
puts "============================================================"
puts "Running tests for trimming strings"
Benchmark.bm(20) do |x|
x.report("s.strip:") { a.each {|s| s = s.strip } }
x.report("s.rstrip.lstrip:") { a.each {|s| s = s.rstrip.lstrip } }
x.report("s.gsub:") { a.each {|s| s = s.gsub(/^\s+|\s+$/, "") } }
x.report("s.sub.sub:") { a.each {|s| s = s.sub(/^\s+/, "").sub(/\s+$/, "") } }
x.report("s.strip!") { a.each {|s| s.strip! } }
x.report("s.rstrip!.lstrip!:") { b.each {|s| s.rstrip! ; s.lstrip! } }
x.report("s.gsub!:") { c.each {|s| s.gsub!(/^\s+|\s+$/, "") } }
x.report("s.sub!.sub!:") { d.each {|s| s.sub!(/^\s+/, "") ; s.sub!(/\s+$/, "") } }
end
Ini hasilnya:
ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-darwin14]
============================================================
Running tests for trimming strings
user system total real
s.strip: 2.690000 0.320000 3.010000 ( 4.048079)
s.rstrip.lstrip: 2.790000 0.060000 2.850000 ( 3.110281)
s.gsub: 13.060000 5.800000 18.860000 ( 19.264533)
s.sub.sub: 9.880000 4.910000 14.790000 ( 14.945006)
s.strip! 2.750000 0.080000 2.830000 ( 2.960402)
s.rstrip!.lstrip!: 2.670000 0.320000 2.990000 ( 3.221094)
s.gsub!: 13.410000 6.490000 19.900000 ( 20.392547)
s.sub!.sub!: 10.260000 5.680000 15.940000 ( 16.411131)