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

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

Chapter 25 Perl and CGI (Common Gateway Interface)
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 15 Introduction to Rails.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8 The Basics of Perl.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Copyright © 2003 Pearson Education, Inc. Slide 1.
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Programming Language Concepts
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.
Chapter Three Arithmetic Expressions and Assignment Statements
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
Pointers and Arrays Chapter 12
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
Types in Ruby and other languages….  Classes and objects (vs prototypes)  Instance variables/encapsulation  Object creation  Object equality/comparison.
 2005 Pearson Education, Inc. All rights reserved Introduction.
Introduction to C Programming
COS 381 Day 21. Agenda Questions?? Resources Source Code Available for examples in Text Book in Blackboard
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
ISBN Chapter 6 Data Types Character Strings Pattern Matching.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
COS 381 Day 22. Agenda Questions?? Resources Source Code Available for examples in Text Book in Blackboard
Guide To UNIX Using Linux Third Edition
JavaScript, Third Edition
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Introduction to C Programming
Scripting with Ruby What is a scripting language? What is Ruby?
Abstract Data Types and Encapsulation Concepts
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
The Ruby Programming Language
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 14 © 2009 by Addison Wesley Longman, Inc Origins and Uses of Ruby - Designed by Yukihiro Matsumoto; released in Use spread rapidly.
Chapter 15 © 2014 by Pearson Education Origins and Uses of Ruby - Designed by Yukihiro Matsumoto; released in Use spread rapidly in Japan.
School of Computing and Information Systems CS 371 Web Application Programming PHP - Basics Serving up web pages.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Lec 6 Data types. Variable: Its data object that is defined and named by the programmer explicitly in a program. Data Types: It’s a class of Dos together.
COMPUTER PROGRAMMING. Functions What is a function? A function is a group of statements that is executed when it is called from some point of the program.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
When you read a sentence, your mind breaks it into tokens—individual words and punctuation marks that convey meaning. Compilers also perform tokenization.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Scripting with Ruby What is a scripting language? What is Ruby?
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Scripting with Ruby What is a scripting language? What is Ruby?
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Fluency with Information Technology Third Edition by Lawrence Snyder Chapter.
Standard Types and Regular Expressions CS 480/680 – Comparative Languages.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Introduction to information systems RUBY dr inż. Tomasz Pieciukiewicz.
Introduction C# program is collection of classes Classes are collection of methods and some statements That statements contains tokens C# includes five.
Ruby: An Introduction Created by Yukihiro Matsumoto in 1993 (named after his birthstone) Pure OO language (even the number 1 is an instance of a class)
14.1 Origins and Uses of Ruby
Java Primer 1: Types, Classes and Operators
14.1 Origins and Uses of Ruby
JavaScript: Functions.
Chapter 14 Introduction to Ruby.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 6 Methods: A Deeper Look
Chapter 8 JavaScript: Control Statements, Part 2
Ruby Testing 2, 11/9/2004.
Corresponds with Chapter 5
Chapter 8 JavaScript: Control Statements, Part 2
Presentation transcript:

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

14-2 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.1 Origins and Uses of Ruby Developed by Yukihiro Matsumoto about 1996 Purely interpreted Somewhat easier learning because of simple structure Notable characteristics Regular expressions based on Perl Dynamic classes based on JavaScript

14-3 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.2 Scalar Types and Their Operations Three categories of data Scalrs Arrays Hashes All values are objects, including numeric values

14-4 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.2 Numeric Literals Numeric data are descendants of class Numeric Float and Integer Fixnum and Bignum Integer literals are Fixnum unless too large, then Bignum Underscores can punctuate integer literals Float literals may not have a decimal point first or last

14-5 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.2 String Literals Single or double quoted Double quoted has escape characters and expression interpolation Expression is specified by #{…} Single quoted have not escape characters or expression interpolation q$...$ for a single quoted string $ can be other characters })] at the end Q$...$ for a double quoted string

14-6 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.2 Variables and Assignment Statements Variable names indicate category of variables Variables are not formally declared and do not have a fixed type An identifier begins with a lower case letter or underscore followed by letters and/or digits and/or underscore Variables are all references to objects An unassigned variable has value nil Named constants are named like variables but have names that begin with a capital letter There are some implicit variables such as $_ Assignment statements in Ruby are the same as in the C/C++/Java family

14-7 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.2 Numeric Operators Standard operators: + - * / % Integer/Integer is integer ** for exponentiation Missing: ++ and – Math module: cos, sin, log, sqrt, … The interactive Ruby interpreter irb takes experssions and responds with the values

14-8 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.2 String Methods Catenation is indicated by + << appends its right operand to the left Similar to an assignment operator += is a synonym capitalize, chop, chomp, upcase, … These create new strings Mutator versions capialize!, chop!, chomp!, upcase! modify the string

14-9 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.2 String Character Access [ index ] Single character reference returns the ASCII code of a character [index]= [first-char, numer-of-chars] gets a substring [first-char, numer-of-chars]= replaces a substring == compares strings for equality based on content equal? compares for the same object eql? compares for type and value compares two strings returning -1 if the first is smaller, 0 if they are equal, +1 if the second is smaller * is used to repeat a string: x * 3 is xxx

14-10 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.3 Screen Output Operator puts displays a string on standard output A new line is added to the output Operator print displays a string without the new line

14-11 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.3 Keyboard Input Function gets gets a line of input from the console (keyboard) gets.chomp returns the next lline of input with out the terminating new line gets.to_i returns the next line of input converted to an integer gets.to_f returns the next line of input converted to a float Example quadeval.rb illustrates console input and output Run with the command ruby quadeval.rb

14-12 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.4 Control Expressions A Boolean expression Any value but nil is considered true Comparison operators Usual: == != = Compare for order: Compare for type and value: eql? Compare for equality of object: equal? Operator precedence and associativity Assignments can be used as control expressions next = gets This is true as long a there is more input Becomes false when input is exhausted

14-13 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.4 Selection and Loop Statements If statement if control-expression statements elsif control-expression statements else statements end elsif can be repeated any number of times (including 0)

14-14 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.4 Unless Reverses if, no else or elsif unless control-expression statements end

14-15 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.4 Case Syntax case expression when value then - statement sequence when value then - statement sequence [else - statement sequence] end

14-16 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.4 Case Semantics Value is matched to whens using === Defined for all built-in classes If the when value is a class, the comparison is true if the case value is an object of the class or one of its superclasses If the value is a range, the case value matches if it is in that range If the when value is a regular expression, the match is based on pattern matching Whens do not cascade, so no break statements are needed

14-17 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.4 Case Expression Syntax case when Boolean expression then expression... when Boolean expression then expression else expression end The first true Boolean expression causes the matching expression to be evaluated as the value of the case The else expression is used if none of the Booleans are true

14-18 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.4 Loops While loop repeats while control expression is true Until loop repeats until control expression is true loop introduces an infinite loop A code block is a sequence of statements delimited by braces or by keywords begin and end The loop keyword is followed by a code block Exit from the loop is by the break statement The next statement causes control to go back to the beginning of the code block Iterator methods are an important repetition construct in Ruby

14-19 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.5 Fundamentals of Arrays Ruby arrays are dynamic in size and can store different types of data in different elements Creating an array Array.new(size) Array.new(size, value) A literal list such as [2, 4, 6] Element access through subscript [sub] Element assignment through [sub]=

14-20 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.5 The for-in Statement Syntax for variable in list statements end The variable takes on each value in the list This is not a reference but a value copy

14-21 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.5 Build-In Methods for Arrays and Lists push inserts at the end of a list pop removes from the end of a list and returns the value unshift inserts at the beginning of a list shift removes from the front of a list and returns the value Arrays catenated with + Method reverse returns a reversed copy Method reverse! reverses the array include? searches an array sort sorts an array, returns a new array

14-22 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.5 An Example The process_names.rb example illustrates using arrays

14-23 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.6 Hashes Hashes are like arrays but use string indexes Indexes are keys and elements are values Hash elements are not ordered Creating a Hash Hash.new Literal hash as in {a=>1, b=>2} Element access using string subscripts Elements are added by using assignment Elements are removed using delete method The clear method removes all elements has_key? checks if a string is a key in a hash Methods keys and values return arrays of the respective components

14-24 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.7 Methods Methods can be defined outside classe When a method is called without an object reference, the default is self

14-25 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.7 Fundamentals of Methods Method syntax def name [( formal-parameters )] statements end Parentheses can be omitted if there are no formal parameters Return statement ends execution of the method With a value, it returns the value as the value of the method If no return ends a method, the last expression is the value of the method

14-26 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.7 Local Variables Variables used in a method are local to the method Global variables with the same name are hidden Local variable names must begin with a lowercase letter or an underscore The lifetime of a local variable from its creation to the end of the execution of the method

14-27 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.7 Parameters Parameters are passed by value unless arrays and hashes Arrays and hashes are passed by reference The number of actual parameters must match the number of formal parameters If the last formal parameter is preceded by an asterisk, it receives all actual parameters not matched to earlier formal parameters Formal parameters can be assigned default values, so the corresponding actual parameter may be omitted If a hash literal is the last actual parameter, the curly braces are not required In this case symbols are conventionally used as the keys A symbol is an unquoted string preceded by a colon Example method median computes the median of an array parameter

14-28 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.8 Basics of Classes Syntax class class-name … end Class names begin with an uppercase letter Instance variables have instances for each object Names begin Constructor is named initialize Example class Stack2_class implements a stack class Members can by dynamically added and removed from a class Method remove_method removes a method

14-29 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.8 Access Control Three levels Public: every method has access Private: only methods of the object have access Private methods may not be invoked with an object reference, so must default to self Different from C++ and Java Protected: only methods of the class or subclasses have access Instance data is private and that cannot be changed Access control methods change access level Invoked without parameters change the default for following methods Invoked with parameters, these are symbols naming methods that have access changed

14-30 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.8 Attributes Method addr_reader takes symbol arguments and defines get methods named after the symbols addr_reader :val Defines a method named val that returns the value Method addr_writer takes symbol arguments and defines an assignment method addr_writer :val Defines a method named val= that allows assignment to the attribute as in obj.val = 17;

14-31 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.8 Inheritance Syntax class My_Subclass < Base_class Access level of a method can be changed in a subclass A method can be made private and, thus, inaccessible through that subclass Modules define namespaces that are often used to hold sets of methods Modules may be mixed in to classes, providing methods to the class by a non-inheritance route

14-32 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.9 Code Blocks and Iterators A code block is a sequence of statements delimited by braces or by do/end A code block can have parameters, listed at the beginning of the block, surrounded by vertical bars: |a, b| A code block may be passed to a method call, following the actual parameters of the call In the method body, a call to yield will executed the block Actual parameters of the call are matched with the block parameters An iterator applies a block to the values in a list

14-33 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14.9 Built-in Iterators each is a method of arrays and takes a block that has one parameter The block is executed with the block parameter taking each element of the list in turn The upto method applies to integers and takes an integer parameter and a block with one parameter The block is executed for each value in the range from the target integer to the actual parameter, inclusive The collect method creates an array from the results of applying a block to each element in an array

14-34 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pattern Matching Pattern matching in Ruby is based on pattern matching in Perl

14-35 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Basics of Pattern Matching Patterns are delimited by slashes =~ is the pattern matching operator The split method is used to split a string with separators given by a regular expression The example word_table.rb uses the split method to divide up input lines into words A hash is used to count word frequencies

14-36 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Remembering Matches Parts of a regular expression pattern can be enclosed in parentheses If there is a match, the variables $1, $2 … hold the strings matched by the parenthesized parts If there is a match, $`, $& and $ hold the part of the target before the match, the part matched and the part after the match

14-37 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Substitutions Method sub substitutes its second parameter for the first match found of the first parameter Method gsub is similar but substitutes for all matches Both methods create new strings sub! and gsub! change the target string The i modifier on a pattern causes the match to ignore letter case