0

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.

2 Answers2

4

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
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
  • Worth mentioning: `2.3.3 :001 > 2.class #=> Fixnum` and `2.3.3 :002 > Fixnum.ancestors #=> [Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject]` – Frederik Spang Sep 29 '18 at 09:50
  • Good answer. For consistency I suggest you change `add(other)` to `puts add(other)`, change `puts 5 + 9` to `5+9` and show what that causes to be displayed. – Cary Swoveland Sep 29 '18 at 22:39
0

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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653