cadience
1/21/2006 5:15:00 PM
Here is a class that I just whipped up while I am also learning (just
grabbed the pickaxe book about an hour ago). This code was inspired by
the fib_up_tp(max) function on page 50. While I can't claim it takes
full advantage of Ruby''s power it nonetheless demonstrates many
facets of the language.
Imagine doing this in C! Even C++ this would be less "clean".
If anyone has any suggestions on taking more advantage of Ruby in the
code below, let me know! Of course, Fibs should inherit an array, and
so fourth (hey, I'm only on page fifty :-p ) , but I believe this gives
a great first look at the power of Ruby's semantics to someone curious
about Ruby.
class Fibs
@foundFibs
def initialize
@foundFibs = Array.new(2, 1)
end
def lastIndex
@foundFibs.size - 1
end
def nextFib
@foundFibs.push(@foundFibs[-2] + @foundFibs[-1])
self.largestFib
end
def largestFib
@foundFibs.last
end
def up_to_num(max)
self.nextFib while @foundFibs.last < max
@foundFibs.find_all{|x| x <= max}
end
def up_to_index(index)
(self.lastIndex + 1).upto(index) {self.nextFib} if index >
self.lastIndex
@foundFibs.first(index + 1)
end
def to_s
s = "["
@foundFibs.each {|name| s += name.to_s + ", "}
s[0..s.size-3] + "]"
end
def length
@foundFibs.length
end
def [](index)
self.up_to_index(index) if index > self.lastIndex
@foundFibs[index]
end
end