Download presentation
Presentation is loading. Please wait.
1
The Ruby Programming Language
Igor Gaponenko March 7, 2003
2
W W W : who, when, why ? Who When Why Yukihiro Matsumoto (Matz)
First introduced in December 1995 Since 2000 Ruby is more popular in Japan than Python Why “…a pragmatic language to get a job done…” “…more powerful than Perl and more truly object-oriented that Python…” “…influenced by Smalltalk, Perl, Python, Eiffel (Ada), Lisp, CLU and Sather...”
3
So what’s the Big difference ? (1)
Language Ruby Added Ruby Took Away Smalltalk Object Orientation: “Everything is an object!“ Ruby, like Smalltalk uses single inheritance. However, Ruby uses a Mix-in concept to mimic multiple inheritance. Ruby isn't as strict as Smalltalk with regard to object, inheritance and class hierarchy; giving a programmer training wheels until true object oriented design is learned. Perl Scripting Power - Clean Object Orientation - Ruby was initially designed with OO in mind, whereas Perl was extended to support objects. Punctuation (Ruby uses prefixes do denote variable scope, not data types). Ruby eliminates a lot of Perl's syntax sugar without losing functionality making Ruby less cryptic. Scope rules in Ruby (default: local) eliminate the need for any 'my' declarations.
4
So what’s the Big difference ? (2)
Language Ruby Added Ruby Took Away Python Exception Handling Exception handling Type coercion between small and long integers Mark and sweep garbage collection instead of a Ref-counter garbage collection. Inheritance / subclassing Ruby's instance variables are prefixed by eliminating the need for 'self' declarations. Python treats types and classes differently, Ruby treats them the same. Tuples Eiffel Object orientation and simple syntax - Ruby is interpreted - Compilation is not required for Ruby Lisp Lambda expressions - Object orientation - All those parentheses
5
What Ruby is good for ? Text processing CGI programming
Network programming XML programming GUI applications AI and Exploratory Mathematics General programming Prototyping Programming education eXtreme programming Etc.
6
Feature Presentation
7
Program Layout : line-oriented
Multiple expressions a = 1 b = 2; c = 3 d = 6 + 7 e = \ + 10 Ruby is able to understand that the statement is incomplete. Tell Ruby explicitly that the statement will continue at the next line
8
Program Layout : code & data
Ruby compiler treats this optional statement as the end of the program’s code <code> __END__ <data> The rest is treated as a data block. It can be read into the running program using the global IO object DATA.
9
Program Layout : BEGIN & END
Optional block(-s) to be executed as the file being loaded before the “normal code” BEGIN { <begin code> } <normal code> END { <end code> Optional block(-s) to be executed after the program finished executing
10
Modules # “file1” module module File1Mod class A ... end
# “main” module require “file1” load “/ruby/modules/file2.rb” a = File1Mod::A.new(...) b = Trig.sin(Trig::PI/2) # “file2” module module Trig PI = def sin(angle) ... end
11
Loading Modules “require” statement means that the module gets compiled at the same time its callers do “load” statement will cause recompilation of the specified module at the run-time. Similar to “eval” in Perl
12
Roles of Modules It’s a way of grouping together:
methods classes constants Modules provide a namespace to prevent name clashes Modules implement the mixin facility => To be discussed later
13
Reserved Words __FILE__ and def end in or self unless __LINE__ begin
defined? ensure module redo super until BEGIN break do false next rescue then when END case else for nil retry true while alias class elsif if not return undef yield
14
What Ruby programs are made from ?
Modules Expressions Classes References Methods Blocks of Code Objects
15
Naming Conventions Begin with low case symbols :
references method names Begin with upper case symbols : Class names Module names Constant names These rules are mostly conventions ! However in some cases they affect the way compiler treats the code (example: constants).
16
References & Objects Everything is an object !
References is the only way to interact with the objects. empty = nil # no object behind a = 1 # numeric object b = a # ‘b’ refers to the same object PI = # here be a constant c = [] # an empty Array object d = MyClass.new # an object of ‘MyClass’ # create an object representing a block of code e = proc { print “A block of code” } e.call # execute the block print e.id # unique object identifier print e.type.name # class name: “Proc”
17
Basic Types ( Classes ) Numbers Strings Arrays Hashes Ranges Symbols
Regular expressions
18
Basic Types : Numbers # Integer numbers : auto-conversion
# Fixnum 123_456 # Fixnum -5 # Negative Fixnum 123_456_789_000_123_456 # Bignum 0xaabb # Hexadecimal # Octal 0b # Binary ?a # Character code ?\C-A # Ctrl-A # Float numbers : map to “double” of the # current architecture # Float 0.0314e2 # Float
19
Basic Types : Strings ‘hello’ # no substitution “hello\n” # insert EOL
“\123mile” # “Smile” %q/no substitution here/ %Q/double quoted string/ # Concatenating strings a = “A &” + “ B” b = “Prefix” ’ and ’ “Suffix” # “Prefix and Suffix” # “here” documents print <<HERE Double quoted here document. It allows substitution. For example: b = #{b} HERE
20
Basic Types : Arrays a = [] # create empty array
some = SomeClass.new # create an object b = [ 1, , “Some string”, some ] # No multi-dimensional arrays – just arrays of references c = [ [ 1, 2, 3 ], ‘a’, 1.2 ] d = [ c, [ 4, 5 ] ] # Using arrays print c[0][0] # 1 print d[0][0][0] # 1 c[1] = ‘b’ # replace ‘a’ with ‘b’
21
Basic Types : Hashes colors = { “red” => 0xf00,
“green” => 0x0f0, “blue” => 0x00f } property = { } # Create an empty hash property[‘WIDTH’] = 10.2 property[...
22
More About Hashes It’s not required that keys of the same hash had the same type What a mess !!! Any objects can be used as keys if: They have the method “hash“ returning a hash value The hash value does not change Hashes keeps references onto objects used as keys The only exception is objects of the class String. They are duplicated.
23
Basic Types : Ranges (as Sequences)
# inclusive range # exclusive range (for last) ‘a’..’z’ 0..anArray.length # Operations digits = 1..10 digits.min # 1 digits.max # 10 digits.include?(5) # true # Converting to arrays (1..5).to_a # [1,2,3,4,5] (“bar”..”bat”).to_a # [“bar”,”bas”,”bat”]
24
More About Ranges Ranges are objects of Range class
Each Range object has two references onto Fixnum objects (not lists) Ranges can be created based on any objects if: the corresponding class defines“succ” method (++ operator in C++) Objects are comparable using “” operator
25
Basic Types : Ranges (as Conditions)
f = File.open( “somefile.txt” ) while f.gets print if /start/../end/ end f.close Print sets of lines of the input file, where the first line in each set contains the word “start” and the last line the word “end” somefile.txt ... Let’s start doing something... do-do-do The end.
26
Basic Types : Ranges (as Intervals)
(1..10) === 5 # true (1..10) === 15 # false (1..10) === # true (‘a’.. ’f’) === ‘b’ # true (‘a’...’f’) === ‘f’ # false
27
Object-Oriented Regexp class
Regular Expressions Full power of Perl + Object-Oriented Regexp class
28
Methods Lambda expressions (functions) …
# Let’s define a trivial method def add( first, second ) first + second end # ...and use it a = add( 1 , 2 ) b = add 1, 2
29
Methods : default parameters
Watch for parameters substitution in strings… def coolFriends( first = “me”, second = “me” ) “#{first} and #{second}” end # Let’s make friends print coolFriends print coolFriends( “Smith” ) print coolFriends( “Smith”, “Wesson” ) # Guess what we’ll see... me and me me and Smith Smith and Wesson
30
Methods : variable-length args
The last (or the only) parameter may get the rest (0..n) arguments. This parameter is an object of Array type. def var( first, *rest ) print “first = “, first, “\n” print “rest has “, rest.length, “ elements\n” for arg in rest print arg, “, “ end # Let’s try this var 1 var 1, 2 # rest = [ 2 ] var 1, 2, 3 # rest = [ 2, 3 ]
31
Methods : associating w/ blocks (1)
A block is called within a method using yield. A blocks is passed as the last parameter of the method. Watch for two methods to pass a block. def executeMe yield end # Let’s try this executeMe { print “Hello! I’m a block.\n” } executeMe do ...
32
Methods : associating w/ blocks (2)
A block may be parameterized by passing parameters to yield. This techniques is used in iterators. def foreachElement(array) for e in array yield e # call a block and pass it a value end # Let’s try this fighters = [ “F-4”, “F-14”, “MIG-23”, “HARRIER” ] foreachElement fighters do |name| print “Got “, name, “\n”
33
Iterators Ruby does not have good loop constructs. There is more powerful technique of iterators. Iterators make use of methods associated with blocks. sum = 0; 10.downto( 0 ) { |x| sum += x } # x = 10,9, ... ,0 10.times { |x| print “X ” } # “X X X X X “ 10.step(16, 2) { |x| print x, “ “ } # “ “ The built-in integer type has these (and more others) iterators. User defined classes may introduce its own iterators or mix-in the Enumerable module to get these iterators “(almost) for free”.
34
If and Case are Expressions ! (1)
In Ruby if and case are not statements (as in C/C++). They are expressions. Remember ‘?’ operator in C++ ? colors = [ “red”, “green”, “blue” ] masks = if someName == “red” 0xf00 else if someName == “green” 0x0f0 0x00f end
35
If and Case are Expressions ! (2)
Here is a combined example illustrating use of ranges in conditional expressions. rating = case votesCast when then Rating::SkipThisOne when then Rating::CouldDoBetter else Rating::Rave end
36
Classes : Constructor # Define the class class Song
def initialize( name, artist, duration ) ... end def play print “Bla-bla-bla...” # Let’s create an object of the class song = Song.new( “Lullaby”, “Me”, ) song.play song.type.name # “Song”
37
Classes : Instance Variables
Instance variables (attributes) are prefixed with class Song def initialize( name, artist, duration ) @name, = name, artist, duration end def name @name # Let’s create an object of the class and get # the name of the song. song = Song.new( “Lullaby”, “Me”, ) print song.name # “Lullaby”
38
Classes : Readable Attrubutes
Another way to define readable attributes class Song attr_reader :name, :artist, :duration def initialize( name, artist, duration ) @name, = name, artist, duration end # Now all attributes are available song = Song.new( “Lullaby”, “Me”, ) print song.name # “Lullaby” print song.artist # “Me”
39
Classes : Writable Attributes
class Song attr_writer :name, :artist, :duration ... end # Now all attributes are modifiable song = Song.new( “Lullaby”, “Me”, ) song.name = “Another one” song.artist = “Him”
40
Classes : Virtual Attributes
class Song ... def durationInMinutes @duration / 60.0 end define durationInMinutes=(duration) @duration = 60.0 * duration # Try virtual attributes song = Song.new( “Lullaby”, “Me”, ) print song.durationInMinutes # “10.0” song.durationInMinutes = 5.5
41
Classes : Class Variables
Class variables (attributes) are prefixed with class Song = 0 def initialize( name, artist, duration ) ... end def play += 1 song = Song.new( “Lullaby”, “Me”, ) song.play # -> 1 song.play # -> 2
42
Classes : Class Methods
Class methods are prefixed with the class name. class Song = 0 ... def Song.numOfPlays end song.play print Song.numOfPlays # “2”
43
Classes : Access Control
Difference from C++ and Java : “private” members are not available to other objects !!! class MyClass ... def method1 # default is public public # explicitly public def method2 protected def method3 # this class and subclasses private def method4 # this _object_ only end
44
Classes : Inheritance Single inheritance only.
class KaraokeSong < Song attr_reader :lyrics def initialize( name, artist, duration, lyrics ) super( name, artist, duration ) @lyrics = lyrics end def play # overload the base class method super song = KaraokeSong.new( “Lullaby”, “Me”, 600.0, “It’s..” ) song.play # play the derived class’s method
45
Mixing Ruby replacement for multiple inheritance.
Note, that “self” is the same as “this” in C++ module Debug def whoAmI? “#{self.type.name} : #{self.id}” end class MyClass include Debug # Include the contents of the module ... # as if all its constants and methods end # were defined by the current class. a = MyClass.new print a.whoAmI? # “MyClass : ”
46
Mixing : Comparison Operators
An “almost free” way to bring a new functionality into a user-defined class. Just include a library module Comparable and provide the only method “” (“spaceship operator). class Song include Comparable # defines: <, >, <=, >=, ==, != ... def (other) self.duration other.duration end c1 = Song.new( “Name1”, “Artist1”, ) c2 = Song.new( “Name2”, “Artist2”, ) if c1 < c2 then c1.play
47
Mixing : Iterators An “almost free” way to bring a full glory of iterators into a user-defined class. Just include a library module Enumerable and provide the only method “each”. class MyCollection include Enumerable private attr :collection # an array w/ elements def each for e yield e end c = MyCollection.new a = c.sort # get a sorted array of MyCollection’s # elements. e = c.find { |e| e.type.name == “Fixnum” }
48
Extending Class Definition
Any (including predefined) classes can be extended at any time. This will affect all existing and new objects unless those objects Are “frozen”. array = [ “a”, “b”, “c”, “d” ] class Array def to_ids ids = [] each { |e| ids << e.id } ids end array.to_ids # [ , , 23456, ] array.freeze unless array.frozen? # it’s stable now copiedArray = array.dup # get modifiable
49
Exceptions Exceptions are objects of Exception class or its subclasses. require “socket” socket = TCPSocket.open(‘ ‘port’) f = File.open(“OutFile.mp3”, “w”) begin while data = socket.read(512) f.write(data) end rescue SystemCallError print “IO failed: “ + $! f.close File.delete(“OutFile.mp3”) raise “IO failed” # produce RuntimeError exception
50
Exceptions : Complete Path
f = File.open(“OutFile.mp3”, “w”) begin # process something rescue Exception1 # handle this particular exception rescue # handle other exceptions else # Congratulations! No errors. ensure # always gets executed. f.close unless f.nil? end
51
Threads & Processes They are available
Threads (light weight processes) Subprocesses (fork, exec) Standard set of threads synchronization methods: Mutexes, Condition variables, Monitors, etc. Problems on Windows: Do not map onto NT native threads – the simulation is clearly not based on a preemptive scheduling mechanism.
52
Misc Extension to C is possible
Lots of existing modules solving various problems Apache Web server module: mod_ryby Documentation and books available Stable releases Still under development Performance
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.