# Nuby: method defined in two classes

**URL:** <https://www.ruby-forum.com/t/nuby-method-defined-in-two-classes/49651>\
**Category:** Ruby\
**Created:** [December 7, 2005, 8:08am UTC](https://www.ruby-forum.com/t/nuby-method-defined-in-two-classes/49651 "2005-12-07T08:08:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![botp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/258eb7/32.png) [@botp](https://www.ruby-forum.com/u/botp)\
**Post date:** [December 7, 2005, 8:08am UTC](https://www.ruby-forum.com/t/nuby-method-defined-in-two-classes/49651/1 "2005-12-07T08:08:16Z")

</div>

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  
asking for something more cleaner/elegant…

thanks and kind regards -botp

code follows…

:~/ruby # cat test1.rb  
#-----------------------------------------------

# [http://acm.uva.es/p/v1/100.html](http://acm.uva.es/p/v1/100.html)

# 3n + 1 problem

#-----------------------------------------------

class Fixnum  
def cycles\_3n\_1  
n = self  
my\_loop do |i|  
break i if n==1  
if n.is\_odd?  
n = 3\*n + 1  
else  
n = n / 2  
end  
end  
end

```
def is_odd?
    self & 1 != 0
end

```

end

class Bignum  
def is\_odd?  
self & 1 != 0  
end  
end

def my\_loop  
c = 1  
loop do  
yield c  
c += 1  
end  
end

def get\_max first, last  
max = -1  
first.upto(last) do |i|  
c = i.cycles\_3n\_1  
max = c if c\>max  
end  
max  
end

puts “from \t To \t Max Cycle \t Elapsed Time (sec)”  
DATA.each do |pair|  
time\_start = Time.now  
i,j = pair.split  
k = 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

---

<div class="post-metadata">

**Author:** ![botp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/258eb7/32.png) [@botp](https://www.ruby-forum.com/u/botp)\
**Post date:** [December 7, 2005, 8:16am UTC](https://www.ruby-forum.com/t/nuby-method-defined-in-two-classes/49651/2 "2005-12-07T08:16:24Z")

</div>

Peña wrote:

> 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 asking for something more cleaner/elegant…

Why not define #is\_odd? on Integer?

---

<div class="post-metadata">

**Author:** ![botp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/258eb7/32.png) [@botp](https://www.ruby-forum.com/u/botp)\
**Post date:** [December 7, 2005, 8:20am UTC](https://www.ruby-forum.com/t/nuby-method-defined-in-two-classes/49651/3 "2005-12-07T08:20:27Z")

</div>

Facets:

Integer#odd?

T.
