Title: Ruby
1Ruby
2History of Ruby
- Parent Languages
- Perl
- Small Talk
- Lisp
- Ada
- Eiffel
3History of Ruby
- Founder and Creator
- Yukihiro Matsumoto
- Created
- Feb. 24,1993
- Latest Release
- Version 1.8.4 in December of 2005
- 1.9 in development
4Why was Ruby Created?
- Make Life much simpler
- Convenience of use for the user, not the
computer. - Code should follow the programmer expectations.
- Very little surprises.
5The Power of Ruby
- Massive Libraries
- Multi-threading
- Garbage collection
- Exception handling
- High portability
- Some compilation but will soon see byte-code
6Naming Conventions
- Similar to Pythons 1st character is a letter or
an underscore, others are alphanumeric or
underscore. - Class names must be capitalized, method names
must start with a lower case letter.
7Reserved Words
Programming Ruby The Pragmatic Programmers Guide
8Data Types
- All data types are classes
- Int, String, Array, Hash,Float
- Int has 2 subcategories
- Bignum
- Fixnum
- Hashes are equivalent to Dictionaries in Python,
and Arrays are essentially Python Lists.
9Naming Syntax
- Variables can be prefixed with a scope identifier
to signify their usage. - No prefix Local.
- _at_ Instance.
- (uppercase) Global.
- _at__at_ Class Variable.
- Uppercase Constant.
_at_size size _at__at_num_instances 0 Config
unix Pi 3.14 tmp a.split
10Naming Conventions
- Built-In modules and classes are Camel Typed.
- MatchData, FileTest, TrueClass, etc.
- Variables are Duck Typed.
- If it walks like a duck and quacks like a duck,
it must be a duck. - A variables value determines its type and its
available set of operations.
11Type Binding
- Everything is Implicit Heap Dynamic.
- Likewise with Python.
- Constants can be reassigned, but with a warning.
- Everything is an object!
- Employs the same dynamic referencing that Python
uses.
L 1,2,3 h l L0 2 puts h 2,2,3
12Type Checking
- Rubys variables are weakly typed, just like
Pythons. - Even constants can be redefined, however this
will cause a warning from the interpreter.
13Blocks
- Rubys blocks generally start with a keyword,
such as def, class,do, and sometimes
begin, and end with end. - Blocks can be passed to functions as a variable.
This can be useful for creating iterators.
14Blocks (continued)
def fibUpTo(max) i1, i2 1, 1
parallel assignment while i1 lt max
yield i1 i1, i2 i2, i1i2 end end
Passing the block f print f,
fibUpTo(1000) f print f, " "
15Assignment Mechanics
- Fits general syntax found in our book
- lttarget_vargtltassignment_opergtltexprgt
- Uses as operator
- Assigns right side to object on left side
16Assignment Mechanics
AB123 Agtgt6 Bgtgt6 A(B12)3 Agtgt6 Bgtgt3
17Assignment Mechanics
- Parallel Assignment is allowed as in Python
- This means this Code works
- Otherwise would have to use a temp variable
a, b b, a
18Assignment Mechanics
- Nested Assignments
- gtgtB1,C2,Dnil,E3
- gtgtB1,C2,Dnil,E3
- gtgtB1,C2,D3,E4
- gtgtB1,C2,D3,E5
- gtgtB1,C2,D3,4,E5
B,(C,D),E1,2,3,4
B,(C,D),E1,2,3,4
B,(C,D),E1,2,3,4
B,(C,D),E1,2,3,4,5
B,(C,D),E1,2,3,4,5
19 Assignment Mechanics
- and - vs , --
- Ruby allows for the first two symbols but not the
last. Code
count 2 count - 2 count Error
20Boolean
- Ruby uses the operator to test for equality
- symbol is used for tested equality in the
Case and When statements. - Standard lt, gt, lt, gt signs also supported.
21Boolean
- Ambiguous allows for the following
- ! and not
- and and
- and or
- Helpful for programmers learning a second
language, but decreases readability
22Boolean
- Expression is not wrapped and no colon
- Expression is either followed by a new line or a
reserved word. - Indentation is still used for readability
- The reserved word end appears at the end of the
block of code.
23Boolean
- ltgt symbol is unique to Ruby
- Returns -1,0, or 1
- Code
3ltgt1 1 1ltgt3 2 1ltgt1 0
24Loops
- Similar to python
- Keywords used
- For
- While
- Until
- Object.eachblock
- Num.step , num.upto(n), num.times
- loop
25The For loop
Python
Ruby
for m in list print m
for m in list do print m end
for num in 0..4 print num end
for num in range(5) print num
26While loop
Python
Ruby
while 1 do break if i tyler end
while 1 if i ben break
27Until
- Resembles a while loop
- Allows more flexibility with the use of
associated block
until Some condition Body end
28Object.each
- A method found in most array/string storage type
objects in ruby. - Iterates through an object
List t,y,l,e,r List.each x print
x.next
Produces u z m f s
29Num iterations
- Use numbers to iterate a specified amount of
times - Possible with FIXNUM class
Produces 0 2 4 6 8 10
0.step(10,2) x print x
5.times do print 1 end
Produces 1 1 1 1 1
30Num.upto(n) compared to C
C
Ruby
0.upto(2) do x print x end
for (int n0 nlt2 n) coutltltn
Both output their respective block variables twice
31loop
- Basic loop statement
- Iterates over a given body
- Requires some sort of break or will run forever
loop Body break
32Other loop constructs
- Retry-start a loop over
- retry if n 1
- Next-used to skip rest of iteration
- next if n 1
33Methods
- Ruby does not support nested method
- Methods are called
- Object.method or object.method()
- Object.method (parameters)
- Also utilize keyword arguments
- Methods are declared in Ruby as follows
- def method
- def method(parameter,parameters2)
- Use of catches any remaining parameters as a
list - Must name all functions with lowercase or will be
a constant not a method.
34Methodology of methods
- In calling a method,Ruby requires
- A receiver --gt receiver
- The Method --gt receiver.method
- Parameters --gt receiver.method(parameters)
- Block --gt receiver.method(parameters)xblock
35Passing to Methods
- Pass By Reference ONLY!
- The word return is NOT used in Ruby.
- The last item modified is returned
def main l 4 a 2 r 1 end
What is returned from the Function to the left?
36Inheritance
- Like C and Python Ruby allows for the
specialization of classes using inheritance.
37Inheritance
- Code
- Notice that class Diamond is a subclass of Gem
and is denoted by the lt - If the super class is not stated ruby assumes it
to be the Object class
class DiamondltGem def initialize(stone,
karat,value,clarity) super(stone, karat,
value) _at_clarity clarity end
end end
38Inheritance
- Like Python and C, inheritance allows for the
programmer to rewrite functions. Ruby will look
for the definition that is closest at hand
starting in the sub classes and working up the
chain into the parent classes. - The parents function can be called using the key
word super
39Inheritance
- Code
- This code calls the parent class Gems function
common_method instead of the function defined in
Diamond
class DiamondltGem def common_method
super _at_clarity end end
40Inheritance
- Single Inheritance only!!!
- Unlike C
- Mixins
- This allows a class to somewhat declare a second
parent without the drawbacks - This is done by including a module in a class
definition
41EVERYTHING OBJECT
- Everything is an object
- Everything belongs to a class
- Example FIXNUM class for numbers
- -5.abs will produce absolute value of -5
42Class Constructs
- Defining classes in Ruby resembles Python
- Classes are an object in Rubys class called
CLASS. - There is no use of the word self, except that
simulated by self - If a method is missing, Ruby uses the method
called method_missingon the original receiver. - Classes and methods are parsed at execution time.
43Notes on Variable scope
- Scope in blocks, loops, and methods
- All variables declared in any of the above are
lost - Retained if declared before execution of a block
or declared global.
ltyler l.each x s t puts x if
t x with the above, we lose s.
s escape block loss ltyler l.each x
s t puts x if t x s is not lost
44Object specific classes
- Powerful construct that ties a class to a
specific object - Quasi-inheritance because object inherits its
original classes And overrides them with any
found in the specific class
S somestring classltltS def delete
print self self end
Invoking s.delete Produces somestringsomestring
45Exception Handling
- Two main forms
- Rescue, Catch and Throw
- Rescue block runs when code in an begin-end block
raises an exception. - Catch and Throw are more flexible ways to handle
exceptions - Exception Class
- Passed whenever an exception is raised.
- Contains the exception name, a backtrace, and the
associated error message.
46Rescue
- Can be extended with else, ensure, and retry
(careful!). - A rescue example from Programming Ruby.
f File.open("testfile") begin .. process
rescue .. handle error else puts
"Congratulations-- no errors!" ensure
f.close unless f.nil? end
47Catch and Throw
def promptAndGet(prompt) print prompt res
readline.chomp throw quitRequested if res
"!" return res end catch quitRequested do
name promptAndGet("Name ") age
promptAndGet("Age ") sex promptAndGet("Sex
") .. process information end
- An example from Programming Ruby.
- Continues to get input until a ! is input.
- Catch and Throw do not have to be in the same
scope, more flexible than try and except.
48CGI
- CGI support is a simple way to make Ruby scripts
available on the Internet - The Ruby executable is used by the web server
when a request for a Ruby script is received. - The CGI module simplifies HTML generation and
browser interaction.
49CGI Example
- Example script with URL http//mysite.com/ex.rhtml
?first_nameben
require "cgi" cgi CGI.new params
cgi.params entered_nameparamsfirst_name cgi.o
ut() do cgi.html() do cgi.head() cgi.body()
do cgi.print ltpgtYou entered , entered_name,
lt/pgt end end end
50SQL
- Ruby can interface with many popular SQL
databases when given the proper modules. - None are available in the default Ruby install.
- Simple MySQL example
require 'mysql' con Mysql.new('localhost',
'my_user', 'secret_pass', 'songs') res
con.query("select from song_info") puts "Artist
\t\t Title" res.each_hash do row puts
row'artist'" \t\t "row'title' end con.close
51Threading
- Rubys threading implementation is very similar
to Python threads. - Ruby also natively supports thread pools,
synchronization, status control, safety levels,
etc.
a_thread Thread.new do 10000.times do
print A end end b_thread Thread.new do
10000.times do print B end end a_thread.j
oin b_thread.join puts All done!
52Ruby on Rails
- Rails is an application server built with Ruby.
- Intended to be used alongside MySQL and Apache.
- Portable to wherever its constituents parts run.
- Quick easy creation of dynamic web content.
- Blogs, eCommerce, CMS, etc.
lthtmlgtltheadgtlttitlegtSamplelt/titlegtlt/headgt ltbodygt lt
10.times do gt ltpgtThis is repeated a total of
10 times.lt/pgt lt end gt lt/bodygt lt/htmlgt