An interpreted language
a.k.a dynamic, scripting
e.g., perl
Object Oriented
Single inheritance
High level
Good support for system calls, regex and CGI
Hello World
#!/usr/bin/env ruby
puts Hello world
Basic Ruby
Everything is an object
Variables are not typed
Automatic memory allocation and garbage
collection
Comments start with # and go to the end of
the line
You have to escape \# if you want them
elsewhere
Control structures
Ifelsifelseend
case when <condition>
then <value> else
end
unless <condition> end
while <condition> end
until <condition> end
#.times (e.g. 5.times())
#.upto(#) (e.g. 3.upto(6))
Multi-word names
End characters
Another Example
class Temperature
Factor = 5.0/9
def store_C(c)
@celsius = c
end
Factor is a constant
5.0 makes it a float
def store_F(f)
@celsius = (f - 32)*Factor
end
def as_C
@celsius
end
def as_F
(@celsius / Factor) + 32
end
end # end of class definition
Last evaluated
statement is
considered the return
value
Second Try
class Temperature
Factor = 5.0/9
attr_accessor :c
def f=(f)
@c = (f - 32) * Factor
end
def f
(@c / Factor) + 32
end
def initialize (c)
@c = c
end
end
t = Temperature.new(25)
puts t.f # 77.0
t.f = 60 # invokes f=()
puts t.c # 15.55
ARGV is a special
array holding the
command-line
tokens
Gets a line
If its not a comment
or a blank line
Print it
Blocks
Allow passing chunks of code in to methods
Receiving method uses yield command to
call passed code (can call yield multiple
times)
Single line blocks enclosed in {}
Multi-line blocks enclosed in doend
Can use parameters
[ 1, 3, 4, 7, 9 ].each {|i| puts i }
Keys = h.keys.sort {|a,b| a <=> b }
url_output =
filename.gsub(/\.txt$/i, ".html")
url = `cat #{filename}`.chomp
cmd = "curl #{url} -o #{url_output}";
puts cmd
`#{cmd}`
end
end
CGI example
require 'cgi'
cgi = CGI.new("html3")
size = cgi.params.size
if size > 0 # processing form
in = cgi.params['t'].first.untaint
cgi.out { cgi.html { cgi.head
cgi.body { "Welcome, #{in}!" }
} }
else
puts <<FORM
Content-type: text/html
<HTML><BODY><FORM>
Enter your name: <INPUT TYPE=TEXT
NAME=t><INPUT TYPE=SUBMIT>
</FORM></BODY></HTML>
FORM
end
No parameters?
Reflection
...to examine aspects of the program from within the
program itself.
#print out all of the objects in our system
ObjectSpace.each_object(Class) {|c| puts c}
#Get all the methods on an object
Some String.methods
#see if an object responds to a certain method
obj.respond_to?(:length)
#see if an object is a type
obj.kind_of?(Numeric)
obj.instance_of?(FixNum)