Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ruby and the tools 740Tools05ClassesObjectsVars Topics Ruby Classes Objects Variables Containers Blocks Iterators Spring 2014 CSCE 740 Software Engineering.

Similar presentations


Presentation on theme: "Ruby and the tools 740Tools05ClassesObjectsVars Topics Ruby Classes Objects Variables Containers Blocks Iterators Spring 2014 CSCE 740 Software Engineering."— Presentation transcript:

1 Ruby and the tools 740Tools05ClassesObjectsVars Topics Ruby Classes Objects Variables Containers Blocks Iterators Spring 2014 CSCE 740 Software Engineering

2 – 2 – CSCE 740 Spring 2014 Tools - Last Time  Ruby Basics  Ruby Regexp New Ruby  Classes  Objects Next Time: System Modelling

3 – 3 – 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)Regular Expressions (download pdf)pdf Namespaces, Source Files, and Distribution (download pdf)Namespaces, Source Files, and Distribution (download pdf)pdf Built-in Classes and Modules (download pdf of the entry for class Array)Built-in Classes and Modules (download pdf of the entry for class Array)pdf Free Content …Free Content … More on reg expr http://www.ruby-doc.org/core-2.1.0/Regexp.htmlhttp://www.ruby-doc.org/core-2.1.0/Regexp.htmlhttp://www.ruby-doc.org/core-2.1.0/Regexp.html http://ruby-doc.org/docs/ProgrammingRuby/

4 – 4 – CSCE 740 Spring 2014 google(ruby 1.9 tutorial) http://ruby-doc.com/docs/ProgrammingRuby/http://ruby-doc.com/docs/ProgrammingRuby/http://ruby-doc.com/docs/ProgrammingRuby/ http://www.ruby-doc.org/stdlib-1.9.3/http://www.ruby-doc.org/stdlib-1.9.3/http://www.ruby-doc.org/stdlib-1.9.3/

5 – 5 – 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 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 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 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

6 – 6 – CSCE 740 Spring 2014 Regexp: Lookahead and Lookbehind

7 – 7 – CSCE 740 Spring 2014 Ruby I/O Already seenAlready seen puts print P On readingOn reading Gets reads line from stdin  variable $_ Iterate over lines of fileline = getsprint line http://ruby-doc.org/docs/ProgrammingRuby/

8 – 8 – CSCE 740 Spring 2014 Processing stdin = ARGF while gets # assigns line to $_ while gets # assigns line to $_ if /Ruby/ # matches against $_ if /Ruby/ # matches against $_ print # prints $_ print # prints $_ endend Now the “ruby way” ARGF.each { |line| print line if line =~ /Ruby/ } http://ruby-doc.org/docs/ProgrammingRuby/

9 – 9 – 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

10 – 10 – CSCE 740 Spring 2014 Classes, 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 endendaSong = Song.new("Bicylops", "Fleck", 260) http://ruby-doc.org/docs/ProgrammingRuby/

11 – 11 – CSCE 740 Spring 2014 aSong = Song.new("Bicylops", "Fleck", 260) aSong.inspect >> # aSong.inspect >> # aSong.to_s >> "# ” http://ruby-doc.org/docs/ProgrammingRuby/

12 – 12 – CSCE 740 Spring 2014 New improved to_s http://ruby-doc.org/docs/ProgrammingRuby/ class Song def to_s “Song: #{@name} -- #{ @artist } ( #{ @duration } )” endendaSong = Song.new("Bicylops", "Fleck", 260) aSong.to_s >> “Song: Bicylops--Fleck (260)”

13 – 13 – CSCE 740 Spring 2014 Inheritance 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 aSong = KaraokeSong.new("My Way", "Sinatra", 225, " And now, the...") aSong.to_s … http://ruby-doc.org/docs/ProgrammingRuby/

14 – 14 – CSCE 740 Spring 2014 overriding to_s http://ruby-doc.org/docs/ProgrammingRuby/ class KarokeSong def to_s “KS: #{@name} -- #{ @artist } ( #{ @duration } ) [#{@lyrics}]” “KS: #{@name} -- #{ @artist } ( #{ @duration } ) [#{@lyrics}]”endendclass KaraokeSong < Song def to_s def to_ssuper + " [#{@lyrics}]“endend

15 – 15 – CSCE 740 Spring 2014 Accessing instance variables Class Song attr_reader :name, :artist, :duration attr_writer :duration…end http://ruby-doc.org/docs/ProgrammingRuby/

16 – 16 – CSCE 740 Spring 2014 class JavaSong { // Java code class JavaSong { // Java code private Duration myDuration; private Duration myDuration; public void setDuration(Duration newDuration) { myDuration = newDuration; myDuration = newDuration; }} class Song class Song attr_writer :durationend aSong = Song.new("Bicylops", "Fleck", 260) aSong.duration = 257 http://ruby-doc.org/docs/ProgrammingRuby/

17 – 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." end http://ruby-doc.org/docs/ProgrammingRuby/

18 – 18 – CSCE 740 Spring 2014 Containers, Blocks, and Iterators ContainersArraysHashes Implementing a SongList Container Blocks and Iterators Implementing Iterators Ruby Compared with C++ and Java Blocks for Transactions Blocks Can Be Closures

19 – 19 – CSCE 740 Spring 2014 Containers Hashes h = { 'dog' => 'canine', 'cat' => 'feline', 'd onkey' => '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 – 20 – 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. http://ruby-doc.org/docs/ProgrammingRuby/

21 – 21 – CSCE 740 Spring 2014 SongList: Initializer & append # Initializer class SongList class SongList def initialize @songs = Array.new @songs = Array.new end endend #append method class SongList def append(aSong) def append(aSong) @songs.push(aSong) @songs.push(aSong) self self end endend http://ruby-doc.org/docs/ProgrammingRuby/

22 – 22 – CSCE 740 Spring 2014 SongList: Using Array methods class SongList def deleteFirst def deleteFirst @songs.shift @songs.shift end end def deleteLast def deleteLast @songs.pop @songs.pop end endend http://ruby-doc.org/docs/ProgrammingRuby/

23 – 23 – CSCE 740 Spring 2014 SongList: [ ] method 1rst version class SongList def [ ](key) def [ ](key) if key.kind_of?(Integer) if key.kind_of?(Integer) @songs[key] @songs[key] else else #... #... end end end

24 – 24 – CSCE 740 Spring 2014 Class Variables class 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 end end def play def play @plays += 1 @plays += 1 @@plays += 1 @@plays += 1 "This song: #@plays plays. Total #@@plays plays. "This song: #@plays plays. Total #@@plays plays. end endend

25 – 25 – CSCE 740 Spring 2014 Class Methods class Example def instMeth # instance method def instMeth # instance method …end def Example.classMeth # class method def Example.classMeth # class method …endend http://ruby-doc.org/docs/ProgrammingRuby/

26 – 26 – CSCE 740 Spring 2014 Singletons 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 endend http://ruby-doc.org/docs/ProgrammingRuby/ Logger.create.id»537766930 Logger.create.id»537766930

27 – 27 – 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.” http://ruby-doc.org/docs/ProgrammingRuby/

28 – 28 – CSCE 740 Spring 2014 Specifying Access class MyClass def method1 # default is 'public' def method1 # default is 'public' #... #... end protected # subsequent methods will be 'protected' protected # subsequent methods will be 'protected' def method2 # will be 'protected' def method2 # will be 'protected' #... #... end private # subsequent methods will be 'private' private # subsequent methods will be 'private' def method3 # will be 'private' def method3 # will be 'private' #... #... end public # subsequent methods will be 'public' public # subsequent methods will be 'public' def method4 # and this will be 'public' def method4 # and this will be 'public' #... #... endend http://ruby-doc.org/docs/ProgrammingRuby/

29 – 29 – CSCE 740 Spring 2014 Blocks a = %w( ant bee cat dog elk ) # create an arraya.each { |animal| puts animal } # iterate over the contents Yield – will be discussed next time [ 'cat', 'dog', 'horse' ].each do |animal| [ 'cat', 'dog', 'horse' ].each do |animal| print animal, " -- " http://ruby-doc.org/docs/ProgrammingRuby/

30 – 30 – CSCE 740 Spring 2014 { puts "Hello" } # this is a blockdo # club.enroll(person) # and so is this club.enroll(person) # and so is this person.socialize end http://ruby-doc.org/docs/ProgrammingRuby/

31 – 31 – CSCE 740 Spring 2014 Blocks 5.times { print "*" }3.upto(6) {|i| print i }('a'..'e').each {|char| print char }*****3456abcde http://ruby-doc.org/docs/ProgrammingRuby/

32 – 32 – CSCE 740 Spring 2014 the [ ] method class SongList def [](key) def [](key) if key.kind_of?(Integer) if key.kind_of?(Integer) return @songs[key] return @songs[key] else else for i in 0...@songs.length for i in 0...@songs.length return @songs[i] if key == @songs[i].name return @songs[i] if key == @songs[i].name end end return nil return nil end endend

33 – 33 – CSCE 740 Spring 2014 the [ ] method version 2 class SongList def [](key) def [](key) if key.kind_of?(Integer) if key.kind_of?(Integer) result = @songs[key] result = @songs[key] else else result = @songs.find { | aSong| key == aSong.name } end result = @songs.find { | aSong| key == aSong.name } end return result return result end endend

34 – 34 – CSCE 740 Spring 2014 the [ ] method version 3 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 } endend

35 – 35 – CSCE 740 Spring 2014 Implementing Iterators def callBlock yield yield endcallBlock { puts "In the block" }ProducesIn the blockIn the block http://ruby-doc.org/docs/ProgrammingRuby/

36 – 36 – CSCE 740 Spring 2014 def fibUpTo(max) i1, i2 = 1, 1 # parallel assignment i1, i2 = 1, 1 # parallel assignment while i1 <= max while i1 <= max yield i1 yield i1 i1, i2 = i2, i1+i2 i1, i2 = i2, i1+i2 end endendfibUpTo(1000) { |f| print f, " " } produces 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

37 – 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 [1, 3, 5, 7, 9].find {|v| v*v > 30 } >> 7

38 – 38 – CSCE 740 Spring 2014 [ 1, 3, 5 ].each { |i| puts i }>>1 3 5 ["H", "A", "L"].collect { |x| x.succ } » ["I", "B", "M"]

39 – 39 – CSCE 740 Spring 2014 Ruby Compared with C++ and Java

40 – 40 – CSCE 740 Spring 2014 Blocks 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() endend File.openAndProcess("testfile", "r") do |aFile| File.openAndProcess("testfile", "r") do |aFile| print while aFile.getsend

41 – 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 endend

42 – 42 – CSCE 740 Spring 2014 Blocks Can Be Closures bStart = Button.new("Start")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... endendbStart = StartButton.new

43 – 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) endendbStart = JukeboxButton.new("Start") { songList.start }bPause = JukeboxButton.new("Pause") { songList.pause }

44 – 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 "


Download ppt "Ruby and the tools 740Tools05ClassesObjectsVars Topics Ruby Classes Objects Variables Containers Blocks Iterators Spring 2014 CSCE 740 Software Engineering."

Similar presentations


Ads by Google