# nuby: method defined in two classes

Discussion in 'Ruby' started by Peña, Botp, Dec 7, 2005.

1. ### Peña, BotpGuest

Hi Friends,

I have the ff code below. It works but you can see that i have =
duplicated the "is_odd?" method on both Fixnum and Bignum. I am just =

thanks and kind regards -botp

code follows...

:~/ruby # cat test1.rb
#-----------------------------------------------
# http://acm.uva.es/p/v1/100.html
# 3n + 1 problem
#-----------------------------------------------

class Fixnum
def cycles_3n_1
n =3D self
my_loop do |i|
break i if n=3D=3D1
if n.is_odd?
n =3D 3*n + 1
else
n =3D n / 2
end
end
end

def is_odd?
self & 1 !=3D 0
end
end

class Bignum
def is_odd?
self & 1 !=3D 0
end
end

def my_loop
c =3D 1
loop do
yield c
c +=3D 1
end
end

def get_max first, last
max =3D -1
first.upto(last) do |i|
c =3D i.cycles_3n_1
max =3D c if c>max
end
max
end

puts "from \t To \t Max Cycle \t Elapsed Time (sec)"
DATA.each do |pair|
time_start =3D Time.now
i,j =3D pair.split
k =3D get_max i.to_i, j.to_i
puts "#{i} \t #{j} \t #{k} \t\t #{Time.now-time_start}"
end

__END__
1 10
100 200
201 210
900 1000
1 1_000_000

:~/ruby # ruby test1.rb
from To Max Cycle Elapsed Time (sec)
1 10 20 0.001598
100 200 125 0.073956
201 210 89 0.005831
900 1000 174 0.094012
1 1_000_000 525 1801.349531

Peña, Botp, Dec 7, 2005

2. ### TransGuest

Facets:

Integer#odd?

T.

Trans, Dec 7, 2005

3. ### Joel VanderWerfGuest

Pe=F1a wrote:
> Hi Friends,
>=20
> I have the ff code below. It works but you can see that i have duplicat=

ed the "is_odd?" method on both Fixnum and Bignum. I am just asking for s=
omething more cleaner/elegant...=20

Why not define #is_odd? on Integer?

--=20
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Joel VanderWerf, Dec 7, 2005