From: Gavin Kistner Date: 2011-08-31T23:46:26+09:00 Subject: Re: Prepend a character to a string in ruby --Boundary_(ID_MLIIzXEvXJKzgtAGjZCCag) Content-type: text/plain; charset=ISO-8859-1; format=flowed Content-transfer-encoding: quoted-printable On Aug 31, 2011, at 08:29 AM, Hassan Schroeder wrote:=0AOn Wed, Aug 31, 2011 at 7:19 AM, Michal Suchanek wrote:=0A=0A> It is sad there is no obvious method for that.=0A=0A= But if it makes you happy, there can be :-)=0A=0Aruby-1.8.7-p352 > class S= tring=0Aruby-1.8.7-p352 ?> def >>(arg)=0Aruby-1.8.7-p352 ?> self.insert(0,= arg)=0Aruby-1.8.7-p352 ?> end=0Aruby-1.8.7-p352 ?> end=0A=3D> nil=0Aruby-= 1.8.7-p352 > string =3D "bar"=0A=3D> "bar"=0Aruby-1.8.7-p352 > string >> "= foo"=0A=3D> "foobar"=0Aruby-1.8.7-p352 >=0A=A0=0ASince we're monkeypatchin= g and mutating anyway, I like reversing the order so that the order of the= arguments is the same as in the result:=0A=0Airb(main):001:0> class Strin= g=0Airb(main):002:1> def >>(other)=0Airb(main):003:2> other.insert(0,self)= =0Airb(main):004:2> end=0Airb(main):005:1> end=0A=3D> nil=0Airb(main):006:= 0> str =3D "bar"=0A=3D> "bar"=0Airb(main):007:0> "foo" >> str=0A=3D> "foob= ar"=0A=0A=0A= --Boundary_(ID_MLIIzXEvXJKzgtAGjZCCag) Content-type: multipart/related; boundary="Boundary_(ID_IQXvUcp/CfbWvNBcjwEn2Q)"; type="text/html" --Boundary_(ID_IQXvUcp/CfbWvNBcjwEn2Q) Content-type: text/html; CHARSET=US-ASCII Content-transfer-encoding: 7BIT
On Aug 31, 2011, at 08:29 AM, Hassan Schroeder <hassan.schroeder@gmail.com> wrote:
On Wed, Aug 31, 2011 at 7:19 AM, Michal Suchanek <hramrach@centrum.cz> wrote:

> It is sad there is no obvious method for that.

But if it makes you happy, there can be :-)

ruby-1.8.7-p352 > class String
ruby-1.8.7-p352 ?> def >>(arg)
ruby-1.8.7-p352 ?> self.insert(0, arg)
ruby-1.8.7-p352 ?> end
ruby-1.8.7-p352 ?> end
=> nil
ruby-1.8.7-p352 > string = "bar"
=> "bar"
ruby-1.8.7-p352 > string >> "foo"
=> "foobar"
ruby-1.8.7-p352 >
 
Since we're monkeypatching and mutating anyway, I like reversing the order so that the order of the arguments is the same as in the result:

irb(main):001:0> class String
irb(main):002:1> def >>(other)
irb(main):003:2> other.insert(0,self)
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> str = "bar"
=> "bar"
irb(main):007:0> "foo" >> str
=> "foobar"


--Boundary_(ID_IQXvUcp/CfbWvNBcjwEn2Q)-- --Boundary_(ID_MLIIzXEvXJKzgtAGjZCCag)--