B
Ben Giddings
That's about my most common error too (it ties with a parse error due
to a missing 'end' statement).
Python to the rescue! See, when your language doesn't have end statements
you can't *possibly* have any of these types of problems, right? *grin*
Ok, but seriously. We have "ruby -w" and "ruby -c" and "unit tests".
So let's have an analogy. Someone writs the following bit of C code:
int do_something(int foo) {
int i;
if (foo > 500) {
printf("Whoa, %d is too many times! I can't do that!", fo);
}
else {
for (i=0; i<foo; i++) {
printf("%d\n", i);
}
}
}
int main(int argc, char **argv) {
do_something(argv[1]);
}
The typical approach of a C programmer would be to try to compile that, and
if they noticed no errors, they'd run it.
The compiler would immediately catch:
* do_something() is being called with an character pointer as an arg, but
is declared as accepting an integer
* The variable used in the printf line "fo" was never declared.
Once the programmer fixed those two issues, the code would do what the
author intended.
The equivalent Ruby code would be:
def do_something(foo)
if foo > 500
puts "Whoa, #{fo} is too many times! I can't do that!"
else
foo.times { |i| puts i }
end
end
do_something(ARGV[0])
"ruby -c" would say this is perfect syntax, which it is. So that's kinda
useless for typos and brainos
"ruby -w" would run it, and it would barf with this message:
foo.rb:4:in `>': undefined method `>' for false:FalseClass (NoMethodError)
from tmp/foo.rb:4:in `do_something'
from tmp/foo.rb:11
The line number is useful, but the message sure isn't. It turns out that
string > number complains about FalseClass. I dunno why. Anyhow, it's
obvious there is *some* error, so presumably the programmer would remember
to 'to_i' the arg to do_something().
Then there's the typo in the "puts" line. Until the person happens to try
an arg greater than 500, they will have no indication the code has a flaw.
Now, would a unit test catch this? If the programmer was careful, maybe.
But maybe not.
So, what advice would you guys give to a C programmer who wants a Ruby tool
to look over lines of code he may rarely execute?
Ben