[Courses] [Ruby] Lesson 0: Installing, References, and your first homework assignment

Joseph Hall joseph.hall at gmail.com
Thu Nov 10 06:05:15 EST 2005


Hello,

My name is Joseph Hall. I've used C++ and Java the most "for real" (at
work), but in college I TA'ed Programming Languages and we went over Java,
Scheme, and Miranda. I also was forced to learn and use Perl at work but I
don't like it. The last couple of weeks at work I've been using a language
called LUA, which is lightweight, fast, stack-based, and the interpreter is
easily embedded in C/C++ apps. Right now I know very little about Ruby. I
want to learn Ruby for fun, not necessarily because I think I'll use it. I
am also interested in participating because I am Laurel's b.f.

I found some simple Ruby on the internet and tweaked it.

---
#!/usr/bin/ruby

def fib(n)
a = 0
b = 1
n.times do
a, b = b, a+b
end
a
end

N = Integer(ARGV.shift || 1)
print "Fib(", N, ") is ", fib(N), "\n"
---


This is computing Fibonacci numbers. I guess the ARGV line is getting
command line parameters, and defaulting to "1" if none are given. Pretty
readable yet compact. Why does N need an explicit Integer()
cast/type/whatever but a and b don't? In Perl I wouldn't need that...

Since I know Scheme, I wanted to compare. I wrote this Scheme to do the same
thing:

---
(define (fib n)
(fib-helper n 1 1))

(define (fib-helper n a b)
(if (<= n 1)
a
(fib-helper (- n 1) b (+ a b))))

(fib 150000)
---

Even though this is a really simple algorithm, you need a helper function in
Scheme in order to really get it right. The "a, b =" syntax in Ruby is
pretty cool.

I would expect the runtime of each to be comparable, but for large N the
Ruby is much faster than Scheme. I know nothing, but I'm venturing a guess
that Ruby is somehow compiled, whereas the Scheme is completely
interpreted...?

Joe


More information about the Courses mailing list