Download presentation
Presentation is loading. Please wait.
Published byAlexander Douglas Modified over 9 years ago
1
Introduction to Ruby CS 480/680 – Comparative Languages
2
Intro to Ruby2 Object Oriented Programming Object: To facilitate implementation independent sharing of code, by providing well- behaved units of functional code For most languages, this unit is the class Specify the behavior of an object, not its implementation
3
Intro to Ruby3 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; };
4
Intro to Ruby4 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.
5
Intro to Ruby5 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
6
Intro to Ruby6 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 object
7
Intro to Ruby7 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.
8
Intro to Ruby8 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); … }; Can be difficult to decide which to choose, since composition will work for any case where inheritance will work.
9
Intro to Ruby9 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 = 7; myObject = 7.0; myObject = ”hello world”; myObject = yourObject;
10
Intro to Ruby10 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;
11
Intro to Ruby11 Ruby Basics Ruby is probably the most object-oriented language around Every built in type is an object with appropriate methods: "gin joint".length 9 "Rick".index("c") 2 -1942.abs 1942 sam.play(aSong) "duh dum, da dum…"
12
Intro to Ruby12 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
13
Intro to Ruby13 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")
14
Intro to Ruby14 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"))
15
Intro to Ruby15 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
16
Intro to Ruby16 Variable Typing and Scope Variables are untyped: var = 7; var *= 2.3; var = ”hello world”; First character indicates scope and some meta- type 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
17
Intro to Ruby17 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!
18
Intro to Ruby18 Ruby Operators See operators.rb
19
Intro to Ruby19 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
20
Intro to Ruby20 Collections (2) Hash – like an array, but the index can be non- numeric Created with {}’s Access like arrays: [] student = { ’name’ => ’John Doe’, ’ID’ => ’123-45-6789’, ’year’ => ’sophomore’, ’age’ => 26 } puts student[’ID’] 123-45-6789
21
Intro to Ruby21 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
22
Intro to Ruby22 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" }
23
Intro to Ruby23 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
24
Intro to Ruby24 Statement Modifiers Single statement loops can be written efficiently with control modifiers: square = square*square while square < 1000 sum = sum * -1 if sum < 0
25
Intro to Ruby25 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 ARGF.each { |line| print line if line =~ /Ruby/ } We’ll talk more about regular expressions later. Blocks and iterators are very powerful in Ruby. More on this later, too.
26
Intro to Ruby26 Basic File I/O Open a file by creating a new File object: infile = File.new(“name”, “mode”) StringModeStart Pos. “r”ReadBeginning “r+”Read/WriteBeginning “w”WriteTruncate/New “w+”Read/WriteTruncate/New “a”WriteEnd/New “a+”Read/WriteEnd/New infile = File.new(“testfile”, “r”) while (line = infile.gets) line.chomp! # do something with line end infile.close
27
Intro to Ruby27 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. Report min, max, and average grade on each assignment
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.