Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom + Method in Ruby String

Tags:

string

ruby

I am trying to modify the Ruby String class, specifically the + method. I want it to return a specific string, such that

 "a" + "b" => "custom_result"

Here's what I have:

class String

  def +(a)
    "custom_result"
  end

end

When I try to require this file in irb, "custom_result" is in my prompt, and I can't execute anything. Any ideas?

like image 571
ragingsquirrel3 Avatar asked Jan 30 '26 02:01

ragingsquirrel3


1 Answers

Well, 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.

like image 179
Jörg W Mittag Avatar answered Jan 31 '26 18:01

Jörg W Mittag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!