From: Robert Klemme Date: 2011-08-31T23:56:58+09:00 Subject: Re: Prepend a character to a string in ruby On Wed, Aug 31, 2011 at 4:46 PM, Gavin Kistner wrote: > On Aug 31, 2011, at 08:29 AM, Hassan Schroeder > wrote: > > On Wed, Aug 31, 2011 at 7:19 AM, Michal Suchanek > 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" That triggered another idea: irb(main):001:0> class String irb(main):002:1> def head=(s) irb(main):003:2> insert 0, s irb(main):004:2> end irb(main):005:1> def tail=(s) irb(main):006:2> self << s irb(main):007:2> end irb(main):008:1> end => nil irb(main):009:0> s = "foo" => "foo" irb(main):010:0> s.head = "begin(" => "begin(" irb(main):011:0> s => "begin(foo" irb(main):012:0> s.tail = ")end" => ")end" irb(main):013:0> s => "begin(foo)end" Note the absence of readers. Reasoning about why left as exercise for the reader. :-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/