Download presentation
Presentation is loading. Please wait.
1
Ruby and the tools 740Tools05ClassesObjectsVars
CSCE 740 Software Engineering Ruby and the tools 740Tools05ClassesObjectsVars Topics Ruby Classes Objects Variables Containers Blocks Iterators Spring 2014
2
Tools - Last Time Ruby Basics Ruby Regexp New Ruby Classes Objects
Next Time: System Modelling Last Time Ruby Basics Ruby Regexp
3
Ruby 1.9 “Buy the book page”
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
4
google(ruby 1.9 tutorial)
5
Programming Ruby TOC 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 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
6
Regexp: Lookahead and Lookbehind
7
Ruby I/O Already seen On reading line = gets print line puts print P
Gets reads line from stdin variable $_ Iterate over lines of file line = gets print line
8
Processing stdin = ARGF
while gets # assigns line to $_ if /Ruby/ # matches against $_ print # prints $_ end Now the “ruby way” ARGF.each { |line| print line if line =~ /Ruby/ }
9
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
10
Classes, Objects, and Variables
class Song def initialize(name, artist, duration) @name = name @artist = artist @duration = duration end aSong = Song.new("Bicylops", "Fleck", 260)
11
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.inspect >> aSong.to_s >> "#<Song:0x401b499c>”
12
New improved to_s class Song def to_s “Song: -- } ( } )” end aSong = Song.new("Bicylops", "Fleck", 260) aSong.to_s >> “Song: Bicylops--Fleck (260)”
13
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 …
14
overriding to_s class KarokeSong def to_s “KS: -- } ( } ) end class KaraokeSong < Song super + "
15
Accessing instance variables
Class Song attr_reader :name, :artist, :duration attr_writer :duration … end
16
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
17
def initialize(name, artist, duration) @name = name @artist = artist
class Song def initialize(name, artist, duration) @name = name @artist = artist @duration = duration @plays = 0 end def play @plays += 1 end
18
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
19
Containers Arrays a = [ , "pie", 99 ] a.type » Array a.length » 3 a[2] » or so methods Hashes h = { 'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine' } h.length » 3 h['cow'] = 'bovine' h['cat'] = 99
20
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.
21
SongList: Initializer & append
# Initializer class SongList def = Array.new end end #append method class SongList def self
22
SongList: Using Array methods
class SongList def end def end
23
SongList: [ ] method 1rst version
class SongList def [ ](key) if else # ... end end end
24
Class Variables class Song = 0 def initialize(name, artist, = = = = 0 end def += 1 += 1 "This song: plays. Total plays. end
25
Class Methods class Example def instMeth # instance method … end
def Example.classMeth # class method
26
Singletons class Logger private_class_method :new @@logger = nil
def Logger.create end Logger.create.id
27
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.”
28
Specifying Access class MyClass def method1 # default is 'public' #...
#... end protected # subsequent methods will be 'protected' def method2 # will be 'protected' private # subsequent methods will be 'private' def method3 # will be 'private' public # subsequent methods will be 'public' def method4 # and this will be 'public'
29
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, " -- "
30
{ puts "Hello" } # this is a block do # club
{ puts "Hello" } # this is a block do # club.enroll(person) # and so is this person.socialize end
31
Blocks 5.times { print "*" } 3.upto(6) {|i| print i }
('a'..'e').each {|char| print char } *****3456abcde
32
the [ ] method class SongList def [](key) if key.kind_of?(Integer) else for i in if key end end return nil end end
33
the [ ] method version 2 class SongList def [](key) if key.kind_of?(Integer) result else result { |aSong| key == aSong.name } end return result end end
34
the [ ] method version 3 class SongList def [](key) if key.kind_of?(Integer) { |aSong| aSong.name == key } end
35
Implementing Iterators
def callBlock yield end callBlock { puts "In the block" } Produces In the block
36
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
37
class Array def find for i in 0
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
[ 1, 3, 5 ]. each { |i| puts i } >> 1 3 5 ["H", "A", "L"]
[ 1, 3, 5 ].each { |i| puts i } >> ["H", "A", "L"].collect { |x| x.succ } » ["I", "B", "M"]
39
Ruby Compared with C++ and Java
40
Blocks for Transactions
class File def File.openAndProcess(*args) f = File.open(*args) yield f f.close() end File.openAndProcess("testfile", "r") do |aFile| print while aFile.gets
41
class File def File. myOpen(. args) aFile = File. new(
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
42
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 bStart = StartButton.new
43
class JukeboxButton < Button def initialize(label, &action) = action end def end bStart = JukeboxButton.new("Start") { songList.start } bPause = JukeboxButton.new("Pause") { songList.pause }
44
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 "
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.