全角スペース対応版strip
書いてみた。
速度的にはまだまだ改善の余地があると思う。
class String def strip_with_full_size_space s = " \s\v" self =~ /^[#{s}]+([^#{s}]+)[#{s}]+$/ ? $1 : self end end
ベンチマーク用のコード。
require 'benchmark' n = 50000 s1 = " 全半混在 " Benchmark.bm do |x| x.report("s1") { n.times do s1.strip_with_full_size_space end } x.report("s1") { n.times do s1.strip end } end
結果。
user system total real s1 0.130000 0.000000 0.130000 ( 0.122258) s1 0.020000 0.000000 0.020000 ( 0.027868)
正規表現のoオプションを外したバージョンの結果。
user system total real s1 0.740000 0.010000 0.750000 ( 0.739665) s1 0.020000 0.000000 0.020000 ( 0.027248)
oオプションの有無で5〜6倍近く実行速度に差が出る。