Rational, Fixnum#power! and negative values

Hi all,

Another question about Rational#power!. I tried this

irb(main):001:0> 2.power!(-2)
NoMethodError: undefined method `power!’ for 2:Fixnum
from (irb):1
irb(main):002:0> require ‘rational’
=> true
irb(main):003:0> 2.power!(-2)
=> 0.25 # huh?

That returns 0.25. However, I would have expected Rational(1, 4).
Based on
the code in rational, it looks like power! is an alias for **, and ** is
an
alias for rpower. So, based on the rpower method, I would think that a
negative value for +other+ would call Rational.new! and return a
Rational.

Or do I have it wrong?

from rational.rb:

class Fixnum
undef quo

If Rational is defined, returns a Rational number instead of a

Fixnum.
def quo(other)
Rational.new!(self,1) / other
end
alias rdiv quo

Returns a Rational number if the result is in fact rational (i.e.

+other+
< 0).
def rpower (other)
if other >= 0
self.power!(other)
else
Rational.new!(self,1)**other
end
end

unless defined? 1.power!
alias power! **
alias ** rpower
end
end

Ideas? Thanks.

Dan

Daniel B. wrote:

=> 0.25 # huh?
class Fixnum
if other >= 0
end

Ideas? Thanks.

Dan

power! is an alias of Fixnum::, then ** is reused as an alias of
rpower
So calling power! is not invoking rpower, it is invoking the original
Fixnum:

Took me a while to figure that out, the alias’ing does at first glance
look like it would chain the methods as you expected

Cheers

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs