Introduction to Ruby CS 480/680 – Comparative Languages.

Slides:



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

Python Objects and Classes
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Programming Languages and Paradigms
Programming Languages and Paradigms The C Programming Language.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS324e - Elements of Graphics and Visualization A Little Java A Little Python.
Road Map Introduction to object oriented programming. Classes
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Introduction to C++ Programming Concept Basic C++ C++ Extension from C.
1 ES 314 Advanced Programming Lec 2 Sept 3 Goals: Complete the discussion of problem Review of C++ Object-oriented design Arrays and pointers.
C++ fundamentals.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
CSC 8310 Programming Languages Meeting 2 September 2/3, 2014.
Review of C++ Programming Part II Sheng-Fang Huang.
The Ruby Programming Language
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
School of Computing and Information Systems CS 371 Web Application Programming PHP - Basics Serving up web pages.
1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
Chapter 6: Functions Starting Out with C++ Early Objects
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Copyright Curt Hill Variables What are they? Why do we need them?
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Abstract Data Types and a review of C++ programming concepts CS 400/600 – Data Structures.
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
RUBY by Ryan Chase.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Functions Starting Out with C++ Early Objects Eighth Edition.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
CS 142 Lecture Notes: RubySlide 1 Basic Ruby Syntax sum = 0 i = 1 while i
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Memory Management.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Review: Two Programming Paradigms
Introduction to Classes
Chapter 4: Writing Classes
Introduction to Classes
CIS 199 Final Review.
Programming Languages and Paradigms
Presentation transcript:

Introduction to Ruby CS 480/680 – Comparative Languages

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

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

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.

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

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

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.

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.

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;

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;

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")  abs  1942 sam.play(aSong)  "duh dum, da dum…"

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

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")

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"))

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

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 – instance variables – class variables Upper case letter – Class name, module name, const

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!

Intro to Ruby18 Ruby Operators  See operators.rb

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

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’ => ’ ’, ’year’ => ’sophomore’, ’age’ => 26 } puts student[’ID’] 

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

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" }

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

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

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.

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

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