From: Pete Date: 2006-06-22T06:44:50+09:00 Subject: Re: The difference between s=s+”a” ans s<< ”a” Most readable + safe for me is e.g.: puts "Hello, #{name}!" puts "your calculation: #{arg1} * #{arg2} = #{arg1 * arg2}" Robert Dober schrieb: > On 6/21/06, Simon Kr�ger wrote: >> >> Robert Dober wrote: >> > On 6/21/06, Alan Moen wrote: >> >> >> >> Hi, >> >> >> >> I wonder what is the difference between s=s+"a" ans s<< "a"? >> > >> > >> > s = s + "a" >> > (1) compute a new String object "s" + a >> > (2) set s as a reference to the newly created object >> > >> > s<<"a" >> > >> > (1) append "a" to the String object s refers to. >> > >> > The latter is much faster and should be prefered when possible (it >> will >> not >> > be possible if s is frozen e.g.) >> >> I think >> s = s + "a" # >> or >> s += "a" >> >> should be the norm as long as you do not know that using it will cause >> you problems (really only performance problems come to my mind) > > > s << "a" > is just what you should do instead > of > s = s+ "a" > unless of course you get paid for GC ;) > > > > Have a look at this: >> -------------------------------------- >> def greet_matz greeting >> greeting << ' matz!' >> puts greeting >> end > > > Calling writer methods on parameters is asking for side effects, that > might > be good or bad, I do not want to discuss that right now, but has > *nothing* > to do with the question of the OP. > > def greet_nobu greeting >> greeting << ' nobu!' >> puts greeting >> end >> >> hello = 'hello' >> greet_matz hello >> greet_nobu hello >> -------------------------------------- >> #=> hello matz! >> #=> hello matz! nobu! >> >> you will get what you expect if you use += > > > Forgive me for being blunt: I will get what I expect if I use <<, I might > not get what you expected. > > cheers >> >> Simon > > > Fortunately I did not state my favorite way to use puts > puts some_variable * 1 << "some text" << ... > ;) > > Cheers > Robert > > > >