Umesh Kushwaha
Umesh Kushwaha

Reputation: 123

How to override Ruby + method?

Just for learning purpose I am trying to override the Ruby + method, but I am not getting the desired output.

class Integer
  def +(my_num)
    "Plus method overridden"
  end
end

puts 5.+(9)

Please let me know what I am doing wrong here.

Upvotes: 0

Views: 1185

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

The Ruby Language Specification allows Integer to have implementation-specific subclasses. See Section 15.2.8.1, lines 27-33.

It looks like your implementation does have such subclasses. In that case, the + method may be overridden in a subclass.

My best guess is that you have an implementation which distinguishes between Fixnums and Bignums, and that our Integer#+ gets overridden by Fixnum#+.

By the way, even if what you were trying to do were working, it wouldn't be overriding, it would be overwriting.

Also note that if what you were trying to do were working, you would have most likely broken your Ruby process, since Integers are fundamental and widely-used all over the place in Ruby.

Upvotes: 0

Danil Speransky
Danil Speransky

Reputation: 30453

It seems you use ruby < 2.4. If so you want to patch Fixnum and not Integer. Be careful as the system itself uses numbers as well.

class Fixnum
  alias_method :add, :+

  def +(other)
    puts 'plus method overridden'
    add(other)
  end
end

puts 5 + 9

Upvotes: 4

Related Questions