Forum: Ruby Rational, Fixnum#power! and negative values

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Daniel B. (Guest)
on 2006-03-30 00:08
(Received via mailing list)
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
ChrisH (Guest)
on 2006-03-30 01:12
(Received via mailing list)
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 topic is locked and can not be replied to.