From: Daniel Carrera Date: 2002-11-21T14:07:27+09:00 Subject: [FAQ] Interpreted vs compiled [FAQ] defining methods anywhere Hello, Gavin suggested I compile the answers to my questions into FAQs. Here they are: 1.- [FAQ] Is Ruby interpreted or compiled? Ruby is interpreted - The parser creates an a syntax tree that is walked. Future plans for Ruby are to move it closer to a compiled language. These include projects to create a RubyVM (Rite, or Ruby 2.0) as well as Cardinal (Ruby frontend for the ParrotVM). Being interpretted does affect the speed of execution to some extent, but Ruby actually does pretty well in the language shootout rankings. Generally not as fast as Perl, but not too much slower. 2.- [FAQ] Why can't I define my methods anywhere? Methods are defined at run-time. Therefore, (unlike Perl) a method cannot be used before it is defined. This will not work: greeting("Daniel") def greeting(name) puts "Hello #{name}" end But this will: def greeting(name) puts "Hello #{name}" end greeting("Daniel") This is a trade-off. It allows you great freedom to modify methods during program execution. For instance: #!/usr/bin/ruby define greeting(name) puts "Hello #{name}" end greeting("Daniel") define greeting(name) puts "Hi #{name}" end greeting("Daniel") Will print: Hello Daniel Hi Daniel Whereas, the Perl equivalent: #!/usr/bin/perl sub greeting { print "Hello $_[0]\n"; } greeting("Daniel") sub greeting { print "Hi $_[0]\n"; } greeting("Daniel") Will print: Hi Daniel Hi Daniel Because Perl's subroutines are defined at compile-time. In Ruby you als ohave the optino of using classes: class Greeting def initialize hello end def hello puts "Hi!" end end Greeting.new # -> Hi! ___ _ ___ | _ \ __ _ _ __ _ _____| | / _\ __ _ _ _ _ _ _____ _ _ __ _ | | \ |/ _` | '_ \| | ___| | | | / _` | '/| '/| ___| '// _` | | |_/ | (_| | | | | | _|_| |__ | |__| (_| | | | | | _|_| || (_| | |____/ \__,_|_| |_|_|_____|____| \___/ \__,_|_| |_| |_____|_| \__,_| Graduate Teaching Assisant. University of Maryland. (301) 405-5137