From: Robert Klemme Date: 2003-07-23T18:02:48+09:00 Subject: Re: Should String#strip take a parameter? "daz" schrieb im Newsbeitrag news:vhs8osad38h515@corp.supernews.com... > > "Xiangrong Fang" wrote: > > > Hi, > > > > I have a question regarding strip. I wrote a DLL in other language, and > > used the following to call the dll function in ruby: > > > > arg = " " * 100 > > myfunc.Call(arg) > > > > after that arg may contain a string such as: > > > > "return value\000" > > > > I used strip, but the strip does not strip away terminating null > > character... > > > > Am I doing something wrong? If I suggest that strip should also strip > > the \000, is it a good idea or not? > > > > Shannon > > > > The only reason for thinking #strip might be relevant > in this situation is that you initialised your buffer > with spaces. > > > class String > def sz_cut! # cut at string-zero terminator > replace(self[/\A[^\0]*/]) > end > end > > p "return value\000 garbage".sz_cut! There is a more efficient implementation of sz_cut!: class String def sz_cut! # cut at string-zero terminator gsub!( /\0.*$/, '' ) end end Cheers robert user system total real test1 change 5.235000 0.031000 5.266000 ( 5.281000) test2 change 5.828000 0.032000 5.860000 ( 5.875000) test1 no change 1.891000 0.000000 1.891000 ( 1.922000) test2 no change 7.078000 0.000000 7.078000 ( 7.125000) require 'benchmark' REP=500000 STR1="foo\0garbage" STR1.freeze STR2="foo.garbage" STR2.freeze def test1(s) s.gsub!( /\0.*$/, '' ) end def test2(s) s.replace(s[/\A[^\0]*/]) end Benchmark.bm(10) do |x| x.report "test1 change" do REP.times { test1 STR1.dup } end x.report "test2 change" do REP.times { test2 STR1.dup } end x.report "test1 no change" do REP.times { test1 STR2.dup } end x.report "test2 no change" do REP.times { test2 STR2.dup } end end