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

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
Advertisements

More about Ruby Maciej Mensfeld Presented by: Maciej Mensfeld More about Ruby dev.mensfeld.pl github.com/mensfeld.
Chapter 2.2 – More about Ruby Maciej Mensfeld Presented by: Maciej Mensfeld More about Ruby dev.mensfeld.pl github.com/mensfeld senior.
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
Python Objects and Classes
Types in Ruby and other languages….  Classes and objects (vs prototypes)  Instance variables/encapsulation  Object creation  Object equality/comparison.
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Class Hierarchy (Inheritance)
And other languages….  Get out a piece of paper  You’ll be tracing some code (quick exercises) as we go along.
Final Review.
Learning Ruby Methods. We’ve seen several so far: puts, gets, chomp, to_s, and even +, -, * and / Usually use dot notation is really just a shortcut.
CSE341: Programming Languages Lecture 20 Blocks & Procs; Inheritance & Overriding Dan Grossman Fall 2011.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
COMP171 Data Structure & Algorithm Tutorial 1 TA: M.Y.Chan.
Principles of Object-Oriented Software Development The language Java.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Scripting with Ruby What is a scripting language? What is Ruby?
Introduction to Ruby CSE 413 Autumn 2008 Credit: Dan Grossman, CSE341.
Ruby (on Rails) CSE 190M, Spring 2009 Week 4. Constructors Writing a new class is simple! Example: class Point end But we may want to initialize state.
Ruby (on Rails) Slides modified by ements-2ed.shtml) 1.
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
The Ruby Programming Language
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
CSC3170 Introduction to Database Systems
Ruby for Java Developers Neal Ford Architect ThoughtWorks Blog: memeagora.blogspot.com.
CMSC 330: Organization of Programming Languages Ruby Hash Tables (and other topics)
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Ruby and the tools Topics Ruby Rails January 15, 2014 CSCE 740 Software Engineering.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
Cory Foy Tampa Code Camp July 15th, 2006 Ruby for C# Developers Cory Foy
Object Oriented Programming: Java Edition By: Samuel Robinson.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
Module 3: Working with Components. Overview An Introduction to Key.NET Framework Development Technologies Creating a Simple.NET Framework Component Creating.
JAVA BASICS Prepared by The Smartpath Information Systems
Perl Language Yize Chen CS354. History Perl was designed by Larry Wall in 1987 as a text processing language Perl has revised several times and becomes.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
+ Ruby and other programming Languages Ronald L. Ramos.
Ruby Objects, Classes and Variables CS 480/680 – Comparative Languages.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Scripting with Ruby What is a scripting language? What is Ruby?
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Standard Types and Regular Expressions CS 480/680 – Comparative Languages.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Ruby Duck Typing, Classes & Inheritance CSE 413 Autumn 2008.
Chapter 2 - OOP Maciej Mensfeld Presented by: Maciej Mensfeld More about OOP dev.mensfeld.pl github.com/mensfeld.
CMSC330 More Ruby. Last lecture Scripting languages Ruby language –Implicit variable declarations –Many control statements –Classes & objects –Strings.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Presented By P.SRIVIDYA 085D1A0552 Programming Language.
Ruby Inheritance and other languages….
Ruby Getting started & Ruby.New Presented by Mario Tayah
types in Ruby and other languages…
Variables All variables hold object references
Classes, Objects, And Variables
Chapter 14 Introduction to Ruby.
Philip Ira Alan Maynard
CSE341: Programming Languages Ruby: Blocks & Procs; Inheritance & Overriding Alan Borning Spring 2018.
Java Programming Language
Ruby Testing 2, 11/9/2004.
Ruby and the tools 740Tools03RubyRegExpr
Ruby and the tools 740Tools05ClassesObjectsVars
CSCE 740 Software Engineering
Code Blocks, Closures, and Continuations
Jim Fawcett CSE687 – Object Oriented Design Spring 2014
Presentation transcript:

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

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

– 3 – CSCE 740 Spring 2014 Ruby 1.9 “Buy the book page” 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

– 4 – CSCE 740 Spring 2014 google(ruby 1.9 tutorial)

– 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 – CSCE 740 Spring 2014 Regexp: Lookahead and Lookbehind

– 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

– 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/ }

– 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 – CSCE 740 Spring 2014 Classes, Objects, and Variables class Song class Song def initialize(name, artist, duration) def initialize(name, artist, = = = = = = duration endendaSong = Song.new("Bicylops", "Fleck", 260)

– 11 – CSCE 740 Spring 2014 aSong = Song.new("Bicylops", "Fleck", 260) aSong.inspect >> # aSong.inspect >> # aSong.to_s >> "# ”

– 12 – CSCE 740 Spring 2014 New improved to_s class Song def to_s “Song: -- } ( } )” endendaSong = Song.new("Bicylops", "Fleck", 260) aSong.to_s >> “Song: Bicylops--Fleck (260)”

– 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, = = lyrics endEnd aSong = KaraokeSong.new("My Way", "Sinatra", 225, " And now, the...") aSong.to_s …

– 14 – CSCE 740 Spring 2014 overriding to_s class KarokeSong def to_s “KS: -- } ( } ) “KS: -- } ( } ) KaraokeSong < Song def to_s def to_ssuper + "

– 15 – CSCE 740 Spring 2014 Accessing instance variables Class Song attr_reader :name, :artist, :duration attr_writer :duration…end

– 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

– 17 – CSCE 740 Spring 2014 class Song class Song = 0 = 0 def initialize(name, artist, duration) def initialize(name, artist, = = = = = = = = 0 end end def play def += += 1 += 1 += 1 "song: plays. Total plays." "song: plays. Total plays." end

– 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 – 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 = [ , "pie", 99 ] a.type » Array a.length » 3 a[2] » or so methods

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

– 21 – CSCE 740 Spring 2014 SongList: Initializer & append # Initializer class SongList class SongList def = = Array.new end endend #append method class SongList def append(aSong) self self end endend

– 22 – CSCE 740 Spring 2014 SongList: Using Array methods class SongList def deleteFirst end end def deleteLast end endend

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

– 24 – CSCE 740 Spring 2014 Class Variables class Song = 0 def initialize(name, artist, duration) def initialize(name, artist, = = = = = = = = 0 end end def play def += += 1 += 1 += 1 "This song: plays. Total plays. "This song: plays. Total plays. end endend

– 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

– 26 – CSCE 740 Spring 2014 Singletons class Logger class Logger private_class_method :new private_class_method :new = nil = nil def Logger.create def Logger.create = new unless = new unless endend Logger.create.id» Logger.create.id»

– 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.”

– 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

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

– 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

– 31 – CSCE 740 Spring 2014 Blocks 5.times { print "*" }3.upto(6) {|i| print i }('a'..'e').each {|char| print char }*****3456abcde

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

– 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 result else else result { | aSong| key == aSong.name } end result { | aSong| key == aSong.name } end return result return result end endend

– 34 – CSCE 740 Spring 2014 the [ ] method version 3 class SongList def [](key) def [](key) if key.kind_of?(Integer) if key.kind_of?(Integer) { |aSong| aSong.name == key } { |aSong| aSong.name == key } endend

– 35 – CSCE 740 Spring 2014 Implementing Iterators def callBlock yield yield endcallBlock { puts "In the block" }ProducesIn the blockIn the block

– 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

– 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 – 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 – CSCE 740 Spring 2014 Ruby Compared with C++ and Java

– 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 – 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 – 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 – CSCE 740 Spring 2014 class JukeboxButton < Button class JukeboxButton < Button def initialize(label, &action) def initialize(label, &action) super(label) = = action end end def buttonPressed endendbStart = JukeboxButton.new("Start") { songList.start }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 "