This throws me a SystemStackError in 1.9.2 Ruby (but works in Rubinius):
class Fixnum
def +(other)
self + other * 2
end
end
but there is no super
for +
(based on other errors).
How can I access the original +
functionality?
This throws me a SystemStackError in 1.9.2 Ruby (but works in Rubinius):
class Fixnum
def +(other)
self + other * 2
end
end
but there is no super
for +
(based on other errors).
How can I access the original +
functionality?
Use alias_method
. Alias Fixnum
's +
to something else, then refer to it in the new +
:
class Fixnum
alias_method :old_add, :+
def +(other)
self.old_add(other) * 2
end
end
alias
vs. alias_method
a lot. –
Anuria end
for the class
it returns nothing—not nil
nothing, as in blank. Trying to look at _
yields the same: nothing. Agreed that this is a horribly bad idea, but interesting solution. –
Anuria Another interesting approach would be to pass a block to Fixnum's module_eval
method. So, for instance:
module FixnumExtend
puts '..loading FixnumExtend module'
Fixnum.module_eval do |m|
alias_method :plus, :+
alias_method :min, :-
alias_method :div, :/
alias_method :mult, :*
alias_method :modu, :%
alias_method :pow, :**
def sqrt
Math.sqrt(self)
end
end
end
Now, after including FixnumExtend throughout my app I can do:
2.plus 2
=> 4
81.sqrt
=> 9
I am using this approach to help my OCR engine recognize handwritten code. It has an easier time with 2.div 2
than 2/2
.
© 2022 - 2024 — McMap. All rights reserved.