Never overload ‘+’ operator of String base class in Ruby

Lets not mess with ruby in our actual projects, Just try in IRB console

class String
  def +(a)
    "custom_result"
  end
end

# Output
ROR: 001 > class String
002?> def +(a)
003?> "custom_result"
004?> end
005?> end
 O/P => :+ 
ROR: custom_result > 'hello'
ROR: custom_result > a = 10
ROR: custom_result > a
ROR: custom_result > a
ROR: custom_result > 

Result: You try once. Well after using this your irb will be out of order, you need to terminate your terminal manually, your ‘exit’ command will not going to work

IRb uses the String class both to print the results and to parse what you type into it. If you mess with that, IRb breaks, that’s not really surprising.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s