introduction to ruby cs 480/680 – comparative languages

27
Introduction to Ruby Introduction to Ruby 480/680 – Comparative Languages 480/680 – Comparative Languages

Upload: alexander-douglas

Post on 26-Dec-2015

226 views

Category:

Documents


3 download

TRANSCRIPT

Introduction to RubyIntroduction to Ruby

CS 480/680 – Comparative LanguagesCS 480/680 – Comparative Languages

Intro to Ruby 2

Object Oriented ProgrammingObject 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

Intro to Ruby 3

An Example From C++An Example From C++class SimpleList {public:

// Insert an integer at the start of the listvirtual bool insertfront(int i) = 0;

// Insert an integer at the end of the listvirtual bool insertend(int i) = 0;

// Get (and delete) the first value in the listvirtual bool getfirst(int &val) = 0;

// Get (and delete) the last value in the listvirtual bool getlast(int &val) = 0;

// Clear the list and free all storagevirtual void clear() = 0;

// Return the number of items in the listvirtual int size() const = 0;

};

Intro to Ruby 4

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

Data Abstraction: MotivationData 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 6

Using ClassesUsing 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

Intro to Ruby 7

Relationships between classesRelationships between classes Inheritance – used when one class has all the

properties of another classclass 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.Base class members can be inherited or overridden by the derived class.

Intro to Ruby 8

Relationships between classes (2)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.

Can be difficult to decide which to choose, since composition will work for any case where inheritance will work.

Intro to Ruby 9

PolymorphismPolymorphism 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;

Intro to Ruby 10

Class variables and instance variablesClass 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 11

Ruby BasicsRuby 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…"

Intro to Ruby 12

Ruby TerminologyRuby 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 13

Code StructureCode 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 resultend

# Time for bed...puts sayGoodnight("John-Boy")puts sayGoodnight("Mary-Ellen")

Intro to Ruby 14

Code Structure (2)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 15

String InterpolationString 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 16

Variable Typing and ScopeVariable 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

Intro to Ruby 17

ScopeScope 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 18

Ruby OperatorsRuby Operators See operators.rb

Intro to Ruby 19

Ruby CollectionsRuby 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 createda = []a = Array.newa = [1, ’cat’, 3]

puts a[2] 3

Intro to Ruby 20

Collections (2)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

Intro to Ruby 21

Collections (3)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 22

Hashes can be a very powerful toolHashes 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 hashwords = Hash.new(0)while (line = gets) words[line] += 1end

words.each {|key, value| print "#{key} ==> #{value}\n"}

Intro to Ruby 23

Control StructuresControl 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 += 1end

Intro to Ruby 24

Statement ModifiersStatement Modifiers Single statement loops can be written

efficiently with control modifiers:

square = square*square  while square < 1000

sum = sum * -1 if sum < 0

Intro to Ruby 25

Reading and WritingReading 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 endend

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.

Intro to Ruby 26

Basic File I/OBasic 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

endinfile.close

Intro to Ruby 27

ExercisesExercises 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