Fall 2012 -- Ruby 1.9
--Short introduction to Ruby:
References:
Getting
started:
Interactive scripts:
- Using your favor editor create a script and save it in a
file with an extension of *.rb
- Using irb (Interactive Ruby Enviornment)
- load 'filename.rb'
- Dir is a useful class. e.g.
- irb(main):003:0> Dir.pwd
=> "/home/eileen/Desktop/DOCUMENT/Courses/471/HW/1SOL"
- irb(main):012:0> Dir.glob("*")
=> ["hw1.py", "hw1_1.c", "a.out", "hw1.rb"]
- irb(main):017:0> Dir.chdir("1SOL")
=> 0
Some important language features:
- Multi-paradigm language
- concurrent and object-oriented
(class-based) are all supported
- dynamically typed
- -- no declaration of variables
- -- type "lives" with objects, not names
- reference model - like smalltalk
- line breaks are
significant and taken as the end
of a statement; a semicolon may be equivalently used
- "end"
terminates all blocks
- indentation is not significant
- "#" begins a comment until the end of line
- && -- logical and operator, != logical Not equal operator
- elsif can be used for "optional parts"
- if n < 5 then
return 10
elsif n < 20 then
return 100
else
return 1000
Example code:
fib.rb
# Recursive definition of the nth fibonacci number
module FibEx
def fib (n)
if (n < 2) then
return 1
else
return fib(n-1) + fib(n-2)
end #End of "if/else"
end #End of "function/method"
def fibi (n)
a = 1
b = 1
s = 1
while (s < n)
s += 1
t = a + b
a = b
b = t
end #End while
return b
end
#End of fibi
def fibf (n)
a = 1
b
= 1
for i in 2 ..
n # i assumes the values 2 to n
t = a + b
a = b
b = t
end #End of for
return b
end #End of fibf
def fibl(n)
a, b = 0, 1
n.times do #Even numbers are objects
a, b = b, a+b
end
return a
end
end #End of Module
# To use methods in IRB we need to include this module
include FibEx
# prints out the results after running in SciTE with "GO" or after
loading in irb or running the script in Ruby shell.
puts fib(8)
puts fibf(8)
puts fibl(8)