A mate of mine just asked me an interesting question. He had written a method
that extended Fixnum and then realised that he wanted it to work for Bignum
as well, but the code is obviously identical.
The only way I could think of to do this was something like …
class Bignum
def Bignum.fred(x)
# Do the calculation with x
end
def fred
Bignum.fred(self)
end
end
class Fixnum
def fred
Bignum.fred(self)
end
end
There HAS to be a better way to do it, but I just can’t think of it.
Effectively, what I would have thought it should be is something like …
class Bignum
def fred
# Do the calculation on self
end
end
class Fixnum
# Coerce self into a Bignum, say “b” and then return b.fred
end
But I can’t think of how I would coerce the Fixnum into a Bignum.
A mate of mine just asked me an interesting question. He had written a
method
that extended Fixnum and then realised that he wanted it to work for
Bignum
as well, but the code is obviously identical.
The only way I could think of to do this was something like …
(snip and snip)
Hmmm. Maybe define a module with nothing but that in it and
include it in both places?
But I can’t think of how I would coerce the Fixnum into a Bignum.
Nor can I offhand. I never stopped to realize till now
that Bignum does not have a ‘new’ method.
Hal
···
----- Original Message -----
From: “Harry Ohlsen” harryo@zip.com.au
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Tuesday, August 06, 2002 3:46 AM
Subject: Writing a method that’s added to both Fixnum and Bignum
they both inherit from integer. can you put it there?
···
On Tue, 2002-08-06 at 02:46, Harry Ohlsen wrote:
A mate of mine just asked me an interesting question. He had written a method
that extended Fixnum and then realised that he wanted it to work for Bignum
as well, but the code is obviously identical.
Or if you don’t want to put it in Integer put your method into a module and
include it into Fixnum and Bignum:
module MyCode
def nice_method
p “hello”
end
end
class Fixnum
include MyCode
end
class Bignum
include MyCode
end
···
–
Justin Johnson
“Tom Sawyer” transami@transami.net wrote in message
news:1028626025.21930.940.camel@silver…
On Tue, 2002-08-06 at 02:46, Harry Ohlsen wrote:
A mate of mine just asked me an interesting question. He had written a
method
that extended Fixnum and then realised that he wanted it to work for
Bignum
as well, but the code is obviously identical.
they both inherit from integer. can you put it there?
Hi, all,
I am writing a Ruby script to do some computation. I need a function
to do similar things like function pow(x,y) in C++? Does anyone know
some information about this?
Thank you in advance.
Yuguo 8.