Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CS 480/680 – Comparative Languages Introduction to Ruby Object Oriented Programming Object: To facilitate implementation independent sharing of code, by providing wellbehaved units of functional code • For most languages, this unit is the class Specify the behavior of an object, not its implementation Intro to Ruby 2 An Example From C++ class SimpleList { public: // Insert an integer at the start of the list virtual bool insertfront(int i) = 0; // Insert an integer at the end of the list virtual bool insertend(int i) = 0; // Get (and delete) the first value in the list virtual bool getfirst(int &val) = 0; // Get (and delete) the last value in the list virtual bool getlast(int &val) = 0; // Clear the list and free all storage virtual void clear() = 0; // Return the number of items in the list virtual int size() const = 0; }; Intro to Ruby 3 Encapsulation How is the SimpleList implemented? • An array with dynamic resizing? An STL vector? A singly-linked list? A doubly-linked list? You don’t need to know the implementation of the class, because it’s behavior has been specified for you. This separation of behavior from implementation is called encapsulation, and is the key principle underlying object oriented programming. Intro to Ruby 4 Data Abstraction: Motivation Focus on the meaning of the operations (behavior) rather than on the implementation User: minimize irrelevant details for clarity Implementer • Restrict users from making false assumptions about behavior • Reserve the ability to make changes later to improve performance Intro to Ruby 5 Using Classes A class is a collection of data and functions (methods) for accessing the data. An object is a specific instance of a class: SimpleList myList; class Intro to Ruby object 6 Relationships between classes Inheritance – used when one class has all the properties of another class class Rectangle { private: int length, width; public: setSize(int newlength, int newwidth) { length = newlength; width = newwidth;} }; class coloredRectangle : public Rectangle { private: string color; public: setColor(string newcolor) {color = newcolor;} }; Base class members can be inherited or overridden by the derived class. Intro to Ruby 7 Relationships between classes (2) Composition – one class containing another class: class Node { private: int value; // The integer value of this node. Node* next; // Pointer to the next node. public: Node(int newvalue = 0) {value = newvalue; next = NULL;} setNext(Node * newnext) {next = newnext;} }; class linkedList { private: Node* head; public: linkedList() {head = NULL); … }; Intro to Ruby Can be difficult to decide which to choose, since composition will work for any case where inheritance will work. 8 Polymorphism Operators and member functions (methods) behave differently, depending on what the parameters are. In C++, polymorphism is implemented using operator overloading Should allow transparency for different data types: myObject myObject myObject myObject Intro to Ruby = = = = 7; 7.0; ”hello world”; yourObject; 9 Class variables and instance variables Most data members are instance variables, each object gets its own independent copy of the variables. Class variables (and constants) are shared by every object/instance of the class: class Student { private: static int total_students; string id, last_name, first_name; … } int Student::total_students = 0; Intro to Ruby 10 Ruby Basics Ruby is probably the most object-oriented language around Every built in type is an object with appropriate methods: "gin joint".length "Rick".index("c") -1942.abs sam.play(aSong) Intro to Ruby 9 2 1942 "duh dum, da dum…" 11 Ruby Terminology Class/instance – the usual definitions • Instance variables – again, what you would expect • Instance methods – have access to instance variables Methods are invoked by sending messages to an object • The object is called the receiver All subroutines/functions are methods • Global methods belong to the Kernel object Intro to Ruby 12 Code Structure No semicolons. One statement per line. • Use \ for line continuation Methods are defined using the keyword def: def sayGoodnight(name) result = "Goodnight, " + name return result end # Time for bed... puts sayGoodnight("John-Boy") puts sayGoodnight("Mary-Ellen") Intro to Ruby 13 Code Structure (2) Parens around method arguments are optional • Generally included for clarity • These are all equivalent: puts sayGoodnight "John-Boy" puts sayGoodnight("John-Boy") puts(sayGoodnight "John-Boy") puts(sayGoodnight("John-Boy")) Intro to Ruby 14 String Interpolation Double quoted strings are interpolated Single quoted strings are not name = ”John Kerry” puts(”Say goodnight, #{name}\n”) Say goodnight John Kerry puts(’Say goodnight, #{name}\n’) Say goodnight, #{name}\n Intro to Ruby 15 Variable Typing and Scope Variables are untyped: var = 7; var *= 2.3; var = ”hello world”; First character indicates scope and some metatype information: • Lower case letter (or _) – local variable, method parameter, or method name • $ – global variables • @ – instance variables • @@ – class variables • Upper case letter – Class name, module name, const Intro to Ruby 16 Scope Local variables only survive until the end of the current block while (var > 0) newvar = var * 2; // newvar created … end // now newvar is gone! Intro to Ruby 17 Ruby Operators See operators.rb Intro to Ruby 18 Ruby Collections Collections are special variables that can hold more than one object • Collections can hold a mix of object types Arrays – standard 0-based indexing • Must be explicitly created a = [] a = Array.new a = [1, ’cat’, 3] puts a[2] 3 Intro to Ruby 19 Collections (2) Hash – like an array, but the index can be nonnumeric • Created with {}’s • Access like arrays: [] student = { ’name’ => ’John Doe’, ’ID’ => ’123-45-6789’, ’year’ => ’sophomore’, ’age’ => 26 } puts student[’ID’] 123-45-6789 Intro to Ruby 20 Collections (3) Hashes and Arrays return the special value nil when you access a non-existent element When you create a hash, you can specify a different default value: myhash = Hash.new(0) This hash will return 0 when you access a non-existent member We’ll see a lot more methods for arrays and hashes later Intro to Ruby 21 Hashes can be a very powerful tool Suppose you wanted to read a file and… • List all of the unique words in the file in alphabetical order • List how many times each word is used The answer is a hash words = Hash.new(0) while (line = gets) words[line] += 1 end words.each {|key, value| print "#{key} ==> #{value}\n" } Intro to Ruby 22 Control Structures The basics (if, while, until, for) are all there: if (count > 10) puts "Try again“ elsif tries == 3 puts "You lose“ else puts "Enter a number“ end while (weight < 100 and numPallets <= 30) pallet = nextPallet() weight += pallet.weight numPallets += 1 end Intro to Ruby 23 Statement Modifiers Single statement loops can be written efficiently with control modifiers: square = square*square sum = sum * -1 Intro to Ruby while square < 1000 if sum < 0 24 Reading and Writing A key strength of interpreted languages is the ability to process text files very quickly • I/O in Ruby (and Perl and Python) is extremely easy printf "Number: %5.2f, String: %s", 1.23, "hello“ Number: 1.23, String: hello while gets if /Ruby/ print end end We’ll talk more about regular expressions later. ARGF.each { |line| Intro to Ruby print line Blocks and iterators are very powerful in Ruby. More on this later, too. if line =~ /Ruby/ } 25 Basic File I/O Open a file by creating a new File object: infile = File.new(“name”, “mode”) String Mode Start Pos. “r” Read Beginning “r+” Read/Write Beginning “w” Write Truncate/New “w+” Read/Write Truncate/New “a” Write End/New “a+” Read/Write End/New infile = File.new(“testfile”, “r”) while (line = infile.gets) line.chomp! # do something with line end infile.close Intro to Ruby 26 Exercises Write a Ruby program that: • Reads a file and echoes it to standard out, removing any lines that start with # Try also accounting for leading whitespace • Reads a file and prints the lines in reverse order • Reads a list of student records (name, ssn, grade1, grade2, grade3,…) and stores them in a hash. Intro to Ruby Report min, max, and average grade on each assignment 27