CSCE 740 Software Engineering Ruby and the tools
CSCE 740 Software Engineering Ruby and the tools 740 Tools 05 Classes. Objects. Vars Topics n Ruby Classes n Objects Variables Containers Blocks Iterators n n Spring 2014
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/ruby 3/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/Programming. Ruby/ CSCE 740 Spring 2014
google(ruby 1. 9 tutorial) • http: //ruby-doc. com/docs/Programming. Ruby/ • 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, Object. Space, 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/Programming. Ruby/ CSCE 740 Spring 2014
Processing stdin while gets if /Ruby/ print 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/Programming. Ruby/ 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 a. Song = Song. new("Bicylops", "Fleck", 260) – 10 – http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
a. Song = Song. new("Bicylops", "Fleck", 260) a. Song. inspect >> #<Song: 0 x 401 b 4924 @duration=260, @artist="Fl eck", @name="Bicylops"> a. Song. to_s – 11 – >> "#<Song: 0 x 401 b 499 c>” http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
New improved to_s class Song def to_s “Song: #{@name} -- #{ @artist } ( #{ @duration } )” end a. Song = Song. new("Bicylops", "Fleck", 260) a. Song. to_s – 12 – >> “Song: Bicylops--Fleck (260)” http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
Inheritance class Karaoke. Song < Song def initialize(name, artist, duration, lyrics) super(name, artist, duration) @lyrics = lyrics end End a. Song = Karaoke. Song. new("My Way", "Sinatra", 225, " And now, the. . . ") a. Song. to_s … – 13 – http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
overriding to_s class Karoke. Song def to_s “KS: #{@name} -- #{ @artist } ( #{ @duration } ) [#{@lyrics}]” end class Karaoke. Song < Song def to_s super + " [#{@lyrics}]“ end – 14 – http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
Accessing instance variables Class Song attr_reader : name, : artist, : duration attr_writer : duration … end – 15 – http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
class Java. Song { // Java code private Duration my. Duration; public void set. Duration(Duration new. Duration) { my. Duration = new. Duration; } } class Song attr_writer : duration end a. Song = Song. new("Bicylops", "Fleck", 260) a. Song. duration = 257 – 16 – http: //ruby-doc. org/docs/Programming. Ruby/ 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. Total #@@plays. " end – 17 – http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
Containers, Blocks, and Iterators Containers Arrays Hashes Implementing a Song. List 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', 'donkey' => '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 Song. List Container append( a. Song ) » list Append the given song to the list. delete. First() » a. Song Remove the first song from the list, returning that song. delete. Last() » a. Song Remove the last song from the list, returning that song. [ an. Index } » a. Song Return the song identified by an. Index, which may be an integer index or a song title. – 20 – http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
Song. List: Initializer & append # Initializer class Song. List def initialize @songs = Array. new end #append method class Song. List def append(a. Song) @songs. push(a. Song) self end – 21 – http: //ruby-doc. org/docs/Programming. Ruby/ end CSCE 740 Spring 2014
Song. List: Using Array methods class Song. List def delete. First @songs. shift end def delete. Last @songs. pop end – 22 – http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
Song. List: [ ] method 1 rst version class Song. List def [ ](key) if key. kind_of? (Integer) @songs[key] else #. . . 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. Total #@@plays. end – 24 – CSCE 740 Spring 2014
Class Methods class Example def inst. Meth # instance method … end def Example. class. Meth # class method … end – 25 – http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
Singletons class Logger private_class_method : new @@logger = nil def Logger. create @@logger = new unless @@logger end Logger. create. id – 26 – » » 537766930 http: //ruby-doc. org/docs/Programming. Ruby/ 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/Programming. Ruby/ CSCE 740 Spring 2014
Specifying Access class My. Class def method 1 # default is 'public' #. . . end protected # subsequent methods will be 'protected' def method 2 # will be 'protected' #. . . end private # subsequent methods will be 'private' def method 3 # will be 'private' #. . . end public # subsequent methods will be 'public' def method 4 # and this will be 'public' #. . . end http: //ruby-doc. org/docs/Programming. Ruby/ – 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/Programming. Ruby/ 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/Programming. Ruby/ CSCE 740 Spring 2014
Blocks 5. times { print "*" } 3. upto(6) {|i| print i } ('a'. . 'e'). each {|char| print char } *****3456 abcde – 31 – http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
the [ ] method class Song. List def [](key) if key. kind_of? (Integer) return @songs[key] else for i in 0. . . @songs. length return @songs[i] if key == @songs[i]. nam end return nil end – 32 – CSCE 740 Spring 2014
the [ ] method version 2 class Song. List def [](key) if key. kind_of? (Integer) result = @songs[key] else result = @songs. find { |a. Song| key == a. Song. name } end return result end – 33 – CSCE 740 Spring 2014
the [ ] method version 3 class Song. List def [](key) return @songs[key] if key. kind_of? (Integer) return @songs. find { |a. Song| a. Song. name == key } end – 34 – CSCE 740 Spring 2014
Implementing Iterators def call. Block yield end call. Block { puts "In the block" } Produces In the block – 35 – http: //ruby-doc. org/docs/Programming. Ruby/ CSCE 740 Spring 2014
def fib. Up. To(max) i 1, i 2 = 1, 1 # parallel assignment while i 1 <= max yield i 1, i 2 = i 2, i 1+i 2 end fib. Up. To(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 [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. open. And. Process(*args) f = File. open(*args) yield f f. close() end File. open. And. Process("testfile", "r") do |a. File| print while a. File. gets end – 40 – CSCE 740 Spring 2014
class File def File. my. Open(*args) a. File = File. new(*args) # If there's a block, pass in the file and close # the file when it returns if block_given? yield a. File. close a. File = nil end return a. File end – 41 – CSCE 740 Spring 2014
Blocks Can Be Closures b. Start = Button. new("Start") b. Pause = Button. new("Pause") class Start. Button < Button def initialize super("Start") # invoke Button's initialize end def button. Pressed # do start actions. . . end b. Start = Start. Button. new – 42 – CSCE 740 Spring 2014
class Jukebox. Button < Button def initialize(label, &action) super(label) @action = action end def button. Pressed @action. call(self) end b. Start = Jukebox. Button. new("Start") { song. List. start } b. Pause = Jukebox. Button. new("Pause") { song. List. pause } – 43 – CSCE 740 Spring 2014
def n. Times(a. Thing) return proc { |n| a. Thing * n } end p 1 = n. Times(23) p 1. call(3) » 69 p 1. call(4) » 92 p 2 = n. Times("Hello ") p 2. call(3) – 44 – » "Hello " CSCE 740 Spring 2014
- Slides: 44