Download Lec05RubyClasses

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CSCE 740 Software Engineering
Ruby and the tools
740Tools05ClassesObjectsVars
Topics






Spring 2014
Ruby Classes
Objects
Variables
Containers
Blocks
Iterators
Tools Last Time
Ruby Basics
Ruby Regexp
–2–
New Ruby
 Classes
 Objects
Next Time: System Modelling
CSCE 740 Spring 2014
Ruby 1.9 “Buy the book page”
http://pragprog.com/book/ruby3/programming-ruby-1-9
Contents and Extracts
• Regular Expressions (download pdf)
• Namespaces, Source Files, and Distribution
(download pdf)
• Built-in Classes and Modules (download pdf of the
entry for class Array)
• Free Content …
More on reg expr
• http://www.ruby-doc.org/core-2.1.0/Regexp.html
–3–
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
google(ruby 1.9 tutorial)
• http://ruby-doc.com/docs/ProgrammingRuby/
• http://www.ruby-doc.org/stdlib-1.9.3/
–4–
CSCE 740 Spring 2014
Programming
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
–5–
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
Distributed Ruby
Built-in Classes and Methods
Standard Library
Object-Oriented Design
Libraries
Network and Web Libraries
Microsoft Windows Support
Embedded Documentation
Interactive Ruby Shell
Support
CSCE 740 Spring 2014
Regexp: Lookahead and Lookbehind
–6–
CSCE 740 Spring 2014
Ruby I/O
• Already seen
•
•
•
puts
print
P
• On reading
•
•
Gets reads line from stdin  variable $_
Iterate over lines of file
line = gets
print line
–7–
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
Processing stdin
while gets
if /Ruby/
print
end
end
= ARGF
# assigns line to $_
# matches against $_
# prints $_
Now the “ruby way”
ARGF.each { |line| print line if line =~ /Ruby/ }
–8–
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
Classes, Objects, Variables
Basic Classes: def, to_s
Inheritance and Messages
Inheritance and Mixins
Objects and Attributes
Writable Attributes
Virtual Attributes
Class Variables and Class Methods
Singletons and Other Constructors
Access Control
Variables
–9–
CSCE 740 Spring 2014
Classes, Objects, and Variables
class Song
def initialize(name, artist, duration)
@name
= name
@artist = artist
@duration = duration
end
end
aSong = Song.new("Bicylops", "Fleck", 260)
– 10 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.inspect >>
#<Song:0x401b4924 @duration=260, @artist=\"Fl
eck\", @name=\"Bicylops\">
aSong.to_s
– 11 –
>> "#<Song:0x401b499c>”
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
New improved to_s
class Song
def to_s
“Song: #{@name} -- #{ @artist } ( #{ @duration } )”
end
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.to_s
– 12 –
>> “Song: Bicylops--Fleck (260)”
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
Inheritance
class KaraokeSong < Song
def initialize(name, artist, duration, lyrics)
super(name, artist, duration)
@lyrics = lyrics
end
End
aSong = KaraokeSong.new("My Way", "Sinatra", 225, "
And now, the...")
aSong.to_s …
– 13 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
overriding to_s
class KarokeSong
def to_s
“KS: #{@name} -- #{ @artist } ( #{ @duration } )
[#{@lyrics}]”
end
end
class KaraokeSong < Song
def to_s
super + " [#{@lyrics}]“
end
end
– 14 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
Accessing instance variables
Class Song
attr_reader :name, :artist, :duration
attr_writer :duration
…
end
– 15 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
class JavaSong {
// Java code
private Duration myDuration;
public void setDuration(Duration newDuration) {
myDuration = newDuration;
}
}
class Song
attr_writer :duration
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.duration = 257
– 16 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
class Song
@@plays = 0
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
@plays = 0
end
def play
@plays += 1
@@plays += 1
"song: #@plays plays. Total #@@plays plays."
end
– 17 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
Containers, Blocks, and Iterators
Containers
Arrays
Hashes
Implementing a SongList Container
Blocks and Iterators
Implementing Iterators
Ruby Compared with C++ and Java
Blocks for Transactions
Blocks Can Be Closures
– 18 –
CSCE 740 Spring 2014
Containers
Arrays
Hashes
a = [ 3.14159, "pie", 99 ]
h = { 'dog' => 'canine',
'cat' => 'feline',
'd
onkey' => 'asinine'
a.type »
Array
a.length » 3
a[2] » 99
}
h.length » 3
h['cow'] = 'bovine'
50 or so methods
– 19 –
h['cat'] = 99
http://www.ruby-doc.org/core-2.1.0/Array.html
CSCE 740 Spring 2014
Implementing a SongList Container
append( aSong ) » list
Append the given song to the list.
deleteFirst() » aSong
Remove the first song from the list, returning that
song.
deleteLast() » aSong
Remove the last song from the list, returning that
song.
[ anIndex } » aSong
Return the song identified by anIndex, which may be
an integer index or a song title.
– 20 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
SongList: Initializer & append
# Initializer
class SongList
def initialize
@songs = Array.new
end
end
#append method
class SongList
def append(aSong)
@songs.push(aSong)
self
end
– 21 –
http://ruby-doc.org/docs/ProgrammingRuby/
end
CSCE 740 Spring 2014
SongList: Using Array methods
class SongList
def deleteFirst
@songs.shift
end
def deleteLast
@songs.pop
end
end
– 22 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
SongList: [ ] method 1rst version
class SongList
def [ ](key)
if key.kind_of?(Integer)
@songs[key]
else
# ...
end
end
end
– 23 –
CSCE 740 Spring 2014
Class Variables
class Song @@plays = 0
def initialize(name, artist, duration)
@name = name
@artist = artist
@duration = duration
@plays = 0
end
def play
@plays += 1
@@plays += 1
"This song: #@plays plays. Total #@@plays plays.
end
end
– 24 –
CSCE 740 Spring 2014
Class Methods
class Example
def instMeth
# instance method
…
end
def Example.classMeth
# class method
…
end
end
– 25 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
Singletons
class Logger
private_class_method
:new
@@logger = nil
def Logger.create
@@logger = new unless @@logger
@@logger
end
end
Logger.create.id
Logger.create.id
– 26 –
»
»
537766930
537766930
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
Access Control
“Public methods can be called by anyone---there is no
access control. Methods are public by default
(except for initialize, which is always private).
Protected methods can be invoked only by objects of
the defining class and its subclasses. Access is kept
within the family.
Private methods cannot be called with an explicit
receiver. Because you cannot specify an object when
using them, private methods can be called only in
the defining class and by direct descendents within
that same object.”
– 27 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
Specifying Access
class MyClass
def method1
# default is 'public'
#...
end
protected
# subsequent methods will be 'protected'
def method2
# will be 'protected'
#...
end
private
# subsequent methods will be 'private'
def method3
# will be 'private'
#...
end
public
# subsequent methods will be 'public'
def method4
# and this will be 'public'
#...
end
end
http://ruby-doc.org/docs/ProgrammingRuby/
– 28 –
CSCE 740 Spring 2014
Blocks
a = %w( ant bee cat dog elk )
# create an array
a.each { |animal| puts animal } # iterate over the contents
Yield – will be discussed next time
[ 'cat', 'dog', 'horse' ].each do |animal|
print animal, " -- "
– 29 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
{ puts "Hello" }
do
# this is a block
#
club.enroll(person) # and so is this
person.socialize
end
– 30 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
Blocks
5.times { print "*" }
3.upto(6) {|i| print i }
('a'..'e').each {|char| print char }
*****3456abcde
– 31 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
the [ ] method
class SongList
def [](key)
if key.kind_of?(Integer)
return @songs[key]
else
for i in [email protected]
return @songs[i] if key == @songs[i].nam
end
end
return nil
end
end
– 32 –
CSCE 740 Spring 2014
the [ ] method version 2
class SongList
def [](key)
if key.kind_of?(Integer)
result = @songs[key]
else
result = @songs.find { |aSong| key == aSong.name }
end
return result
end
end
– 33 –
CSCE 740 Spring 2014
the [ ] method version 3
class SongList
def [](key)
return @songs[key] if key.kind_of?(Integer)
return @songs.find { |aSong| aSong.name == key }
end
end
– 34 –
CSCE 740 Spring 2014
Implementing Iterators
def callBlock
yield
yield
end
callBlock { puts "In the block" }
Produces
In the block
In the block
– 35 –
http://ruby-doc.org/docs/ProgrammingRuby/
CSCE 740 Spring 2014
def fibUpTo(max)
i1, i2 = 1, 1
# parallel assignment
while i1 <= max
yield i1
i1, i2 = i2, i1+i2
end
end
fibUpTo(1000) { |f| print f, " " }
produces 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
– 36 –
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
– 37 –
CSCE 740 Spring 2014
[ 1, 3, 5 ].each { |i| puts i }
>>
135
["H", "A", "L"].collect { |x| x.succ }
»
["I", "B", "M"]
– 38 –
CSCE 740 Spring 2014
Ruby Compared with C++ and Java
– 39 –
CSCE 740 Spring 2014
Blocks for Transactions
class File
def File.openAndProcess(*args)
f = File.open(*args)
yield f
f.close()
end
end
File.openAndProcess("testfile", "r") do |aFile|
print while aFile.gets
end
– 40 –
CSCE 740 Spring 2014
class File
def File.myOpen(*args)
aFile = File.new(*args)
# If there's a block, pass in the file and close
# the file when it returns
if block_given?
yield aFile
aFile.close
aFile = nil
end
return aFile
end
– 41 –
CSCE 740 Spring 2014
Blocks Can Be Closures
bStart = Button.new("Start")
bPause = Button.new("Pause")
class StartButton < Button
def initialize
super("Start")
# invoke Button's initialize
end
def buttonPressed
# do start actions...
end
end
bStart = StartButton.new
– 42 –
CSCE 740 Spring 2014
class JukeboxButton < Button
def initialize(label, &action)
super(label)
@action = action
end
def buttonPressed
@action.call(self)
end
end
bStart = JukeboxButton.new("Start") { songList.start }
bPause = JukeboxButton.new("Pause") { songList.pause }
– 43 –
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)
– 44 –
»
"Hello Hello Hello "
CSCE 740 Spring 2014
Related documents