Académique Documents
Professionnel Documents
Culture Documents
Introduction to Ruby
CMSC 330
Introduction
!
Books on Ruby
Major application
Text processing
CMSC 330
CMSC 330
1 2 3 4 5 6 7 8 9 10 ...
87 92 93 95 94 89 89 86 76 87
66 67 69 69 73 70 69 70 70 71
77 80 81 82 84 80 79 78 73 79
1 4 5 6 8 4 3 3 -2 4
0 0 0 0 0 0 0 0 0 0
12 15 16 17 19 15 14 13 8 14
0.00 0.00 0.00 0.00 0.00 0.02 0.00 0.74 0.19 0.00
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
0 0 0 0 0 0 0 0 0 0
2.5 3.5 4.1 3.6 5.9 5.3 3.6 4.4 4.1 2.3
9 10 13 9 18 20 14 17 9 8
M M M M M M M M M M
M M M M M M M M M M
7 3 2 3 3 6 7 10 9 8
18 18 18 18 18 138 1 18 18 1
12 17 17 12 25 23 16 23 13 10
CMSC 330
A Simple Example
!
Language Basics
comments begin with #, go to end of line # This is a ruby program x = 37 y = x + 5 print(y) print("\n") line break separates expressions (can also use ; to be safe)
10
% ruby -w ruby1.rb 42 %
CMSC 330 9
the -w will cause Ruby to print a bit more if something bad happens type in Ruby programs one line at a time, and watch as each line is executed irb(main):001:0> 3+4 => 7 irb(main):002:0> print("hello\n") hello => nil
# run program
CMSC 330
11
Tradeoffs?
Explicit Declarations Higher overhead Helps prevent typos Forces programmer to document types Implicit Declarations Lower overhead Easy to mistype variable name Figures out types of variables automatically
x, y; x = 37; y = x + 5;
CMSC 330
13
CMSC 330
14
Methods in Ruby
Methods are declared with def...end
def sayN(message, n) i = 0 while i < n puts message i = i + 1 end return i end x = sayN("hello", 3) puts(x) (Methods should begin with lowercase letter and be defined before they are called)
CMSC 330 15
Formal parameters
Parameters used in the body of the method message, n in our example
Actual parameters
Arguments passed in to the method at a call "hello", 3 in our example
CMSC 330
16
What is True?
!
The guard of a conditional is the expression that determines which branch is taken
if grade >= 90 then ...
Guard
!
17
CMSC 330
CMSC 330
CMSC 330
19
CMSC 330
20
while i>n break next puts message generates a string (cf. to_i) redo end IO.foreach(filename) { |x| code puts x block }
case x when 1, 3..5 when 2, 6..8 end does not need 'break' 21
Everything is an Object
!
Class names begin with an uppercase letter The new method creates an object
s = String.new creates a new String and makes s
refer to it
3 + 4
infix
notation for invoke the + method of 3 on argument 4 are instances of String are objects with a new method
"programming".length
strings
String.new
classes
(4.13).class
use floating
CMSC 330 23 CMSC 330
the class method to get the class for an object point numbers are instances of Float
24
Objects are data Classes are types (the kind of data which things are) But in Ruby, classes themselves are objects!
Object 10 -3.30 "CMSC 330" String.new Fixnum String Fixnum Float String String Class Class Class
Since classes are objects, you can manipulate them however you like
if p then x = String else x = Time end # Time is
y = x.new # another class # creates a String or a Time, # depending upon p
Fixnum, Float, String, etc., (including Class), are objects of type Class
25 CMSC 330
CMSC 330
What is a Program?
!
nil has methods like to_s, but not other methods that
dont make sense
irb(main):006:0> @x + 2 NoMethodError: undefined method `+' for nil:NilClass
CMSC 330 27
28
29
CMSC 330
Tradeoffs?
Static types More work to do when writing code Helps prevent some subtle errors Fewer programs type check Dynamic types Less work when writing code Can use objects incorrectly and not realize until execution More programs type check
CMSC 330
31
CMSC 330
32
def to_s return "(" + @x.to_s + "," + @y.to_s + ")" end end
Ruby does issue an exception or warning if classes defines more than one initialize method
But last initialize method defined is the valid one
instantiation
Inheritance
!
Recall classes begin with an uppercase letter inspect converts any instance to a string
irb(main):033:0> p.inspect => "#<Point:0x54574 @y=4, @x=7>"
CMSC 330
CMSC 330
36
super( ) in Ruby
!
class Global @@x = 0 def Global.inc @@x = @@x + 1; $x = $x + 1 end def Global.get return @@x end end
CMSC 330
37
CMSC 330
Ruby has a bunch of global variables that are implicitly set by methods The most insidious one: $_
Default method return, argument in many cases
Example
gets print # implicitly reads input into $_ # implicitly writes $_
!
Here-documents
s = <<END This is a text message on multiple lines and typing \\n is annoying END
CMSC 330
39
CMSC 330
40
a string
CMSC 330
42
"hello".sub("h", "j")
Replace Use
new string with s's contents except newline at end of line removed
!
first occurrence of "h" by "j" in string gsub ("global" sub) to replace all occurrences array of substrings delimited by tab
"r1\tr2\t\tr3".split("\t")
Return
removes newline from s methods ending in ! modify the object Another convention: methods ending in ? observe the object
Regular Expressions!
44
For
x = "groundhog" ; y = x
x = "groundhog" ; y = x
!
But for
x = "groundhog" y = String.new(x)
x y
(reference)
x
(reference)
"groundhog"
(object)
Ruby would cause an object copy Unnecessary in Java since Strings are final
"groundhog"
Object copy
CMSC 330
Reference copy
45 CMSC 330 46
String Equality
!
x y
!
(reference)
x
(reference)
"groundhog"
(object)
"groundhog"
If references are compared (physical equality) the first would return false but the second true If objects are compared both would return true
47
Its always important to know whether youre doing a reference or object copy
And physical or structural comparison
CMSC 330
CMSC 330
48
Comparing Equality
Language Java C Ruby Ocaml Python Scheme Visual Basic .NET Physical equality
a == b a == b a.equal?(b) a == b a is b (eq? a b) a Is b
Summary
Structural equality
a.equals(b) *a == *b a == b a=b a == b (equal? a b) a=b
! !
CMSC 330
49
CMSC 330
50