Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't >> prepend strings in Ruby?

Tags:

ruby

In ruby, you can append strings using <<:

>> "Hello" << "World"
=> "HelloWorld"

So why can't you prepend them using >>?

>> "Hello" >> "World"
NoMethodError: undefined method `>>' for "Hello":String

I realise String doesn't have the >> method defined, but what's the reasoning behind that?

like image 322
Simon Avatar asked Mar 28 '11 13:03

Simon


1 Answers

Ruby 1.9.3 added a String#prepend method.

The proposal about adding prepend[1] also included the ">>" method, and there's some discussion on the thread about that implementation [2]:

Matz says: " >> is interesting notation did not think about it."

sorya says: "This patch is out it had been discussed several times towards the IRC"

However at the end of the thread, the conclusion was to accept String#prepend, and that "other proposals including String # >> are pending."

I couldn't find any other discussion about it though... anyone else?

Personally, I like it, and it's trivial to add:

class String
  def >> (s)
    s.prepend(self)
  end
end

The result:

>> "Hello" >> "World"
=> "HelloWorld"

[1] http://bugs.ruby-lang.org/issues/3675

[2] http://translate.google.com/translate?hl=en&sl=ja&tl=en&u=http%3A%2F%2Fbugs.ruby-lang.org%2Fissues%2F3675

like image 187
Patrick Smith Avatar answered Oct 21 '22 03:10

Patrick Smith