Ruby and the tools 740Tools05ClassesObjectsVars Topics Ruby Classes Objects Variables Containers...
-
Upload
jonah-byrd -
Category
Documents
-
view
217 -
download
1
Transcript of Ruby and the tools 740Tools05ClassesObjectsVars Topics Ruby Classes Objects Variables Containers...
Ruby and the tools740Tools05ClassesObjectsVars
Ruby and the tools740Tools05ClassesObjectsVars
TopicsTopics
Ruby Classes Objects Variables Containers Blocks Iterators
Spring 2014
CSCE 740 Software Engineering
– 2 – CSCE 740 Spring 2014
Tools - Tools -
Last TimeLast Time
Ruby BasicsRuby Basics
Ruby RegexpRuby Regexp
New RubyNew Ruby
ClassesClasses
ObjectsObjects
Next Time: System Modelling Next Time: System Modelling
– 3 – CSCE 740 Spring 2014
Ruby 1.9 “Buy the book page”Ruby 1.9 “Buy the book page”
http://pragprog.com/book/ruby3/programming-ruby-1-9
Contents and ExtractsContents and Extracts
• Regular Expressions (download Regular Expressions (download pdf))
• Namespaces, Source Files, and Distribution Namespaces, Source Files, and Distribution (download (download pdf))
• Built-in Classes and Modules (download Built-in Classes and Modules (download pdf of the of the entry for class Array)entry for class Array)
• Free Content …Free Content …
More on reg exprMore on reg expr
• http://www.ruby-doc.org/core-2.1.0/Regexp.html
http://ruby-doc.org/docs/ProgrammingRuby/
– 4 – CSCE 740 Spring 2014
google(ruby 1.9 tutorial)google(ruby 1.9 tutorial)
• http://ruby-doc.com/docs/ProgrammingRuby/
• http://www.ruby-doc.org/stdlib-1.9.3/ http://www.ruby-doc.org/stdlib-1.9.3/
– 5 – CSCE 740 Spring 2014
Programming Ruby TOCProgramming Ruby TOC
Foreword Preface Roadmap Ruby.new Classes, Objects, and Variables Containers, Blocks, and Iterators Standard Types More About Methods Expressions Exceptions, Catch, and Throw Modules Basic Input and Output Threads and Processes When Trouble Strikes
Ruby and Its World Ruby and the Web Ruby Tk Ruby and Microsoft Windows Extending Ruby The Ruby Language Classes and Objects Locking Ruby in the Safe Reflection, ObjectSpace, and Reflection, ObjectSpace, and Distributed Ruby Distributed Ruby Built-in Classes and Built-in Classes and Methods Methods Standard Library Standard Library Object-Oriented Design Object-Oriented Design Libraries Libraries Network and Web Libraries Network and Web Libraries Microsoft Windows Support Microsoft Windows Support Embedded Documentation Embedded Documentation Interactive Ruby Shell Interactive Ruby Shell SupportSupport
– 6 – CSCE 740 Spring 2014
Regexp: Lookahead and LookbehindRegexp: Lookahead and Lookbehind
– 7 – CSCE 740 Spring 2014
Ruby I/ORuby I/O
• Already seenAlready seen• puts• print • P
• On readingOn reading• Gets reads line from stdin variable $_• Iterate over lines of file
line = gets line = gets
print lineprint line
http://ruby-doc.org/docs/ProgrammingRuby/
– 8 – CSCE 740 Spring 2014
Processing stdin = ARGFProcessing stdin = ARGF
while gets while gets # assigns line to $_ # assigns line to $_
if /Ruby/ if /Ruby/ # matches against $_ # matches against $_
print print # prints $_ # prints $_
end end
endend
Now the “ruby way”Now the “ruby way”
ARGF.each { |line| print line if line =~ /Ruby/ }ARGF.each { |line| print line if line =~ /Ruby/ }
http://ruby-doc.org/docs/ProgrammingRuby/
– 9 – CSCE 740 Spring 2014
Classes, Objects, VariablesClasses, Objects, Variables
Basic Classes: def, to_sBasic Classes: def, to_s
Inheritance and MessagesInheritance and Messages
Inheritance and MixinsInheritance and Mixins
Objects and AttributesObjects and Attributes
Writable AttributesWritable Attributes
Virtual AttributesVirtual Attributes
Class Variables and Class MethodsClass Variables and Class Methods
Singletons and Other ConstructorsSingletons and Other Constructors
Access ControlAccess Control
VariablesVariables
– 10 – CSCE 740 Spring 2014
Classes, Objects, and VariablesClasses, Objects, and Variables
class Song class Song
def initialize(name, artist, duration) def initialize(name, artist, duration)
@name = name @name = name
@artist = artist @artist = artist
@duration = duration @duration = duration
endend
endend
aSong = Song.new("Bicylops", "Fleck", 260)aSong = Song.new("Bicylops", "Fleck", 260)
http://ruby-doc.org/docs/ProgrammingRuby/
– 11 – CSCE 740 Spring 2014
aSong = Song.new("Bicylops", "Fleck", 260)aSong = Song.new("Bicylops", "Fleck", 260)
aSong.inspect >> aSong.inspect >> #<Song:0x401b4924 @duration=260, @artist=\"Fleck\", #<Song:0x401b4924 @duration=260, @artist=\"Fleck\", @name=\"Bicylops\">@name=\"Bicylops\">
aSong.to_s >> "#<Song:0x401b499c>”aSong.to_s >> "#<Song:0x401b499c>”
http://ruby-doc.org/docs/ProgrammingRuby/
– 12 – CSCE 740 Spring 2014
New improved to_sNew improved to_s
http://ruby-doc.org/docs/ProgrammingRuby/
class Songclass Song
def to_sdef to_s
““Song: #{@name} -- #{ @artist } ( #{ @duration } Song: #{@name} -- #{ @artist } ( #{ @duration } )”)”
endend
endend
aSong = Song.new("Bicylops", "Fleck", 260)aSong = Song.new("Bicylops", "Fleck", 260)
aSong.to_s >> “Song: Bicylops--Fleck (260)”aSong.to_s >> “Song: Bicylops--Fleck (260)”
– 13 – CSCE 740 Spring 2014
InheritanceInheritance
class KaraokeSong < Song class KaraokeSong < Song
def initialize(name, artist, duration, lyrics) def initialize(name, artist, duration, lyrics)
super(name, artist, duration) super(name, artist, duration)
@lyrics = lyrics @lyrics = lyrics
endend
EndEnd
aSong = KaraokeSong.new("My Way", "Sinatra", 225, "aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")And now, the...")
aSong.to_s …aSong.to_s …
http://ruby-doc.org/docs/ProgrammingRuby/
– 14 – CSCE 740 Spring 2014
overriding to_soverriding to_s
http://ruby-doc.org/docs/ProgrammingRuby/
class KarokeSongclass KarokeSongdef to_sdef to_s
“ “KS: #{@name} -- #{ @artist } ( #{ @duration } KS: #{@name} -- #{ @artist } ( #{ @duration } ) ) [#{@lyrics}]”[#{@lyrics}]”endend
endend
class KaraokeSong < Songclass KaraokeSong < Song def to_s def to_s
super + " [#{@lyrics}]“super + " [#{@lyrics}]“endend
endend
– 15 – CSCE 740 Spring 2014
Accessing instance variablesAccessing instance variables
Class SongClass Song
attr_reader :name, :artist, :durationattr_reader :name, :artist, :duration
attr_writer :durationattr_writer :duration
……
end end
http://ruby-doc.org/docs/ProgrammingRuby/
– 16 – CSCE 740 Spring 2014
class JavaSong { // Java code class JavaSong { // Java code
private Duration myDuration; private Duration myDuration;
public void setDuration(Duration newDuration) {public void setDuration(Duration newDuration) {
myDuration = newDuration; myDuration = newDuration;
} }
}}
class Song class Song
attr_writer :duration attr_writer :duration
endend
aSong = Song.new("Bicylops", "Fleck", 260) aSong = Song.new("Bicylops", "Fleck", 260) aSong.duration = 257aSong.duration = 257
http://ruby-doc.org/docs/ProgrammingRuby/
– 17 – CSCE 740 Spring 2014
class Song class Song @@plays = 0 @@plays = 0 def initialize(name, artist, duration) def initialize(name, artist, duration)
@name = name @name = name @artist = artist @artist = artist @duration = duration @duration = duration @plays = 0 @plays = 0
end end def play def play
@plays += 1 @plays += 1 @@plays += 1 @@plays += 1
"song: #@plays plays. Total #@@plays plays." "song: #@plays plays. Total #@@plays plays." endend
http://ruby-doc.org/docs/ProgrammingRuby/
– 18 – CSCE 740 Spring 2014
Containers, Blocks, and IteratorsContainers, Blocks, and Iterators
ContainersContainers
ArraysArrays
HashesHashes
Implementing a SongList ContainerImplementing a SongList Container
Blocks and IteratorsBlocks and Iterators
Implementing IteratorsImplementing Iterators
Ruby Compared with C++ and JavaRuby Compared with C++ and Java
Blocks for TransactionsBlocks for Transactions
Blocks Can Be ClosuresBlocks Can Be Closures
– 19 – CSCE 740 Spring 2014
ContainersContainers
Hashes
h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine'
}
h.length » 3
h['cow'] = 'bovine'
h['cat'] = 99
Arrays
a = [ 3.14159, "pie", 99 ]
a.type » Array
a.length » 3
a[2] » 99
50 or so methods
http://www.ruby-doc.org/core-2.1.0/Array.html
– 20 – CSCE 740 Spring 2014
Implementing a SongList ContainerImplementing a SongList Container
append( aSong ) » list append( aSong ) » list
Append the given song to the list. Append the given song to the list.
deleteFirst() » aSong deleteFirst() » aSong
Remove the first song from the list, returning that Remove the first song from the list, returning that song. song.
deleteLast() » aSong deleteLast() » aSong
Remove the last song from the list, returning that Remove the last song from the list, returning that song. song.
[ anIndex } » aSong [ anIndex } » aSong
Return the song identified by Return the song identified by anIndexanIndex, which may be , which may be an integer index or a song title. an integer index or a song title.
http://ruby-doc.org/docs/ProgrammingRuby/
– 21 – CSCE 740 Spring 2014
SongList: Initializer & appendSongList: Initializer & append# Initializer# Initializer
class SongList class SongList
def initializedef initialize
@songs = Array.new@songs = Array.new
end end
endend
#append method#append method
class SongListclass SongList
def append(aSong)def append(aSong)
@songs.push(aSong)@songs.push(aSong)
selfself
end end
endendhttp://ruby-doc.org/docs/ProgrammingRuby/
– 22 – CSCE 740 Spring 2014
SongList: Using Array methodsSongList: Using Array methods
class SongListclass SongList
def deleteFirstdef deleteFirst
endend
def deleteLastdef deleteLast
end end
endend
http://ruby-doc.org/docs/ProgrammingRuby/
– 23 – CSCE 740 Spring 2014
SongList: [ ] method 1rst versionSongList: [ ] method 1rst version
class SongListclass SongList
def [ ](key)def [ ](key)
if key.kind_of?(Integer)if key.kind_of?(Integer)
@songs[key]@songs[key]
elseelse
# ...# ...
endend
end end
endend
– 24 – CSCE 740 Spring 2014
Class VariablesClass Variables
class Song @@plays = 0class Song @@plays = 0 def initialize(name, artist, duration)def initialize(name, artist, duration) @name = name@name = name @artist = artist@artist = artist @duration = duration@duration = duration @plays = 0@plays = 0 endend def playdef play @plays += 1@plays += 1 @@plays += 1@@plays += 1 "This song: #@plays plays. Total #@@plays plays."This song: #@plays plays. Total #@@plays plays. endendendend
– 25 – CSCE 740 Spring 2014
Class MethodsClass Methods
class Example class Example
def instMeth def instMeth # instance method # instance method
……
end end
def Example.classMeth def Example.classMeth # class method # class method
……
end end
endend
http://ruby-doc.org/docs/ProgrammingRuby/
– 26 – CSCE 740 Spring 2014
SingletonsSingletons
class Logger class Logger
private_class_method :new private_class_method :new
@@logger = nil @@logger = nil
def Logger.create def Logger.create
@@logger = new unless @@logger @@logger = new unless @@logger
@@logger @@logger
end end
endend
http://ruby-doc.org/docs/ProgrammingRuby/
Logger.create.id » 537766930 Logger.create.id » 537766930
– 27 – CSCE 740 Spring 2014
Access Control Access Control
““Public methods can be called by anyone---there is no Public methods can be called by anyone---there is no access control. Methods are public by default access control. Methods are public by default (except for initialize, which is always private). (except for initialize, which is always private).
Protected methods can be invoked only by objects of Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept the defining class and its subclasses. Access is kept within the family. within the family.
Private methods cannot be called with an explicit Private methods cannot be called with an explicit receiver. Because you cannot specify an object when receiver. Because you cannot specify an object when using them, private methods can be called only in using them, private methods can be called only in the defining class and by direct descendents within the defining class and by direct descendents within that same object.”that same object.”
http://ruby-doc.org/docs/ProgrammingRuby/
– 28 – CSCE 740 Spring 2014
Specifying Access Specifying Access class MyClass class MyClass def method1 def method1 # default is 'public' # default is 'public'
#... #... end end
protected protected # subsequent methods will be 'protected' # subsequent methods will be 'protected' def method2 def method2 # will be 'protected' # will be 'protected'
#... #... end end
private private # subsequent methods will be 'private' # subsequent methods will be 'private' def method3 def method3 # will be 'private' # will be 'private'
#... #... end end
public public # subsequent methods will be 'public' # subsequent methods will be 'public' def method4 def method4 # and this will be 'public' # and this will be 'public'
#... #... end end
endend
http://ruby-doc.org/docs/ProgrammingRuby/
– 29 – CSCE 740 Spring 2014
BlocksBlocks
a = %w( ant bee cat dog elk ) # create an array a = %w( ant bee cat dog elk ) # create an array
a.each { |animal| puts animal } # iterate over the contentsa.each { |animal| puts animal } # iterate over the contents
Yield – will be discussed next timeYield – will be discussed next time
[ 'cat', 'dog', 'horse' ].each do |animal| [ 'cat', 'dog', 'horse' ].each do |animal|
print animal, " -- "print animal, " -- "
http://ruby-doc.org/docs/ProgrammingRuby/
– 30 – CSCE 740 Spring 2014
{ puts "Hello" } # this is a block { puts "Hello" } # this is a block
do #do #
club.enroll(person) # and so is this club.enroll(person) # and so is this
person.socialize person.socialize
endend
http://ruby-doc.org/docs/ProgrammingRuby/
– 31 – CSCE 740 Spring 2014
BlocksBlocks
5.times { print "*" } 5.times { print "*" }
3.upto(6) {|i| print i } 3.upto(6) {|i| print i }
('a'..'e').each {|char| print char }('a'..'e').each {|char| print char }
*****3456abcde*****3456abcde
http://ruby-doc.org/docs/ProgrammingRuby/
– 32 – CSCE 740 Spring 2014
the [ ] method the [ ] method
class SongListclass SongList
def [](key)def [](key)
if key.kind_of?(Integer)if key.kind_of?(Integer)
return @songs[key]return @songs[key]
elseelse
for i in [email protected] i in [email protected]
return @songs[i] if key == @songs[i].namereturn @songs[i] if key == @songs[i].name
endend
endend
return nilreturn nil
end end
endend
– 33 – CSCE 740 Spring 2014
the [ ] method version 2the [ ] method version 2
class SongListclass SongList
def [](key)def [](key)
if key.kind_of?(Integer)if key.kind_of?(Integer)
result = @songs[key]result = @songs[key]
elseelse
result = @songs.find { |result = @songs.find { |aSong| key == aSong.name aSong| key == aSong.name } } endend
return resultreturn result
end end
endend
– 34 – CSCE 740 Spring 2014
the [ ] method version 3the [ ] method version 3
class SongList class SongList
def [](key) def [](key)
return @songs[key] if key.kind_of?(Integer) return @songs[key] if key.kind_of?(Integer)
return @songs.find { |aSong| aSong.name == key } return @songs.find { |aSong| aSong.name == key }
end end
endend
– 35 – CSCE 740 Spring 2014
Implementing IteratorsImplementing Iterators
def callBlockdef callBlock
yieldyield
yield yield
end end
callBlock { puts "In the block" }callBlock { puts "In the block" }
ProducesProduces
In the blockIn the block
In the blockIn the blockhttp://ruby-doc.org/docs/ProgrammingRuby/
– 36 – CSCE 740 Spring 2014
def fibUpTo(max)def fibUpTo(max)
i1, i2 = 1, 1 # parallel assignmenti1, i2 = 1, 1 # parallel assignment
while i1 <= maxwhile i1 <= max
yield i1yield i1
i1, i2 = i2, i1+i2i1, i2 = i2, i1+i2
end end
end end
fibUpTo(1000) { |f| print f, " " }fibUpTo(1000) { |f| print f, " " }
produces 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987produces 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
– 37 – CSCE 740 Spring 2014
class Array
def find
for i in 0...size
value = self[i]
return value if yield(value)
end
return nil
end
end
[1, 3, 5, 7, 9].find {|v| v*v > 30 } >> 7
– 38 – CSCE 740 Spring 2014
[ 1, 3, 5 ].each { |i| puts i }[ 1, 3, 5 ].each { |i| puts i } >>>> 1 3 51 3 5
["H", "A", "L"].collect { |x| x.succ } ["H", "A", "L"].collect { |x| x.succ }
»
["I", "B", "M"]
– 39 – CSCE 740 Spring 2014
Ruby Compared with C++ and JavaRuby Compared with C++ and Java
– 40 – CSCE 740 Spring 2014
Blocks for TransactionsBlocks for Transactions
class File class File
def File.openAndProcess(*args) def File.openAndProcess(*args)
f = File.open(*args) f = File.open(*args)
yield f yield f
f.close() f.close()
end end
end end
File.openAndProcess("testfile", "r") do |aFile| File.openAndProcess("testfile", "r") do |aFile|
print while aFile.gets print while aFile.gets
endend
– 41 – CSCE 740 Spring 2014
class File class File
def File.myOpen(*args) def File.myOpen(*args)
aFile = File.new(*args) aFile = File.new(*args)
# If there's a block, pass in the file and close # If there's a block, pass in the file and close
# the file when it returns # the file when it returns
if block_given? if block_given?
yield aFile yield aFile
aFile.close aFile.close
aFile = nil aFile = nil
end end
return aFile return aFile
end end
endend
– 42 – CSCE 740 Spring 2014
Blocks Can Be ClosuresBlocks Can Be Closures
bStart = Button.new("Start") bStart = Button.new("Start")
bPause = Button.new("Pause")bPause = Button.new("Pause")
class StartButton < Button class StartButton < Button
def initialize def initialize
super("Start") # invoke Button's initialize super("Start") # invoke Button's initialize
end end
def buttonPressed def buttonPressed
# do start actions... # do start actions...
end end
end end
bStart = StartButton.newbStart = StartButton.new
– 43 – CSCE 740 Spring 2014
class JukeboxButton < Button class JukeboxButton < Button
def initialize(label, &action) def initialize(label, &action)
super(label) super(label)
@action = action @action = action
end end
def buttonPressed def buttonPressed
@action.call(self) @action.call(self)
end end
end end
bStart = JukeboxButton.new("Start") { songList.start }bStart = JukeboxButton.new("Start") { songList.start }
bPause = JukeboxButton.new("Pause") { songList.pause }bPause = JukeboxButton.new("Pause") { songList.pause }
– 44 – CSCE 740 Spring 2014
def nTimes(aThing)
return proc { |n| aThing * n }
end
p1 = nTimes(23)
p1.call(3) » 69
p1.call(4) » 92
p2 = nTimes("Hello ")
p2.call(3) » "Hello Hello Hello "