[Courses] [Ruby] Lesson 0: Installing, References,
and your first homework assignment
laurel.fan at gmail.com
Thu Nov 17 02:45:32 EST 2005
On 11/9/05, Joseph Hall <joseph.hall at gmail.com> wrote:
> I found some simple Ruby on the internet and tweaked it.
> def fib(n)
> a = 0
> b = 1
> n.times do
> a, b = b, a+b
> 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
Yep. ARGV is a list containing all of the command line parameters
(not including the filename of the program itself, which will be
different for C programmers. That's in $0).
> Why does N need an explicit Integer()
> cast/type/whatever but a and b don't?
> In Perl I wouldn't need that...
This is because Ruby is strongly typed but Perl isn't. Ruby is also
dynamically typed (and it has "duck typing" which I haven't seen in
any other mainstream language), which is why you didn't have to say
int a = 0
You assigned it to a Fixnum, so a is a Fixnum.
However, for N, the result of ARGV.shift is a String, so it needs to
be turned into an integer.
> 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
No, ruby is completely interpreted. I think there are ways of
compiling it, at least into bytecode, but those are fairly obscure.
Maybe it's just because the scheme is recursive and the perl is not?
I don't know Scheme that well (my obligatory college class functional
language was ML), but does it look like the Scheme interpreter should
be doing a tail call optimization?
More information about the Courses