Chapter 15 © 2014 by Pearson Education 1 15.1 Origins and Uses of Ruby - Designed by Yukihiro Matsumoto; released in 1996 - Use spread rapidly in Japan.

Slides:



Advertisements
Similar presentations
Chapter 25 Perl and CGI (Common Gateway Interface)
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
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.
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
COS 381 Day 19. Agenda  Assignment 5 Posted Due April 7  Exam 3 which was originally scheduled for Apr 4 is going to on April 13 XML & Perl (Chap 8-10)
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Guide To UNIX Using Linux Third Edition
JavaScript, Third Edition
Scripting with Ruby What is a scripting language? What is Ruby?
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
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.
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.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
Chapter 14 © 2009 by Addison Wesley Longman, Inc Origins and Uses of Ruby - Designed by Yukihiro Matsumoto; released in Use spread rapidly.
Ryan Chu. Arithmetic Expressions Arithmetic expressions consist of operators, operands, parentheses, and function calls. The purpose is to specify an.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Ruby! Useful as a scripting language – script: A small program meant for one time use – Targeted towards small to medium size projects Use by: – Amazon,
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
2440: 211 Interactive Web Programming Expressions & Operators.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
Input, Output, and Processing
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Ruby on Rails. What is Ruby? Programming Language Object-oriented Interpreted.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
JavaScript, Fourth Edition
Scripting with Ruby What is a scripting language? What is Ruby?
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
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.
Arrays and Lists. What is an Array? Arrays are linear data structures whose elements are referenced with subscripts. Just about all programming languages.
Perl Chapter 3 Conditional statements. Control Expressions Control expressions – interpreted as T/F (evaluated as strings or numbers) – simple, relational,
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
CMSC330 More Ruby. Last lecture Scripting languages Ruby language –Implicit variable declarations –Many control statements –Classes & objects –Strings.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Definition of the Programming Language CPRL
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
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
CS-104 Final Exam Review Victor Norman.
14.1 Origins and Uses of Ruby
JavaScript Syntax and Semantics
Chapter 14 Introduction to Ruby.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Introduction to C++ Programming
Chapter 8 JavaScript: Control Statements, Part 2
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
Statement-Level Control Structures
Python Primer 1: Types and Operators
Chapter 8 JavaScript: Control Statements, Part 2
Presentation transcript:

Chapter 15 © 2014 by Pearson Education Origins and Uses of Ruby - Designed by Yukihiro Matsumoto; released in Use spread rapidly in Japan - Use is now growing in part because of its use in Rails - A pure object-oriented purely interpreted scripting language - Related to JavaScript, but not closely 15.2 Scalar Types and Their Operations - There are three categories of data types: scalars, arrays, and hashes - Two categories of scalars, numerics and strings - All numeric types are descendants of the Numeric class - Integers: Fixnum (usually 32 bits) and Bignum

Chapter 15 © 2014 by Pearson Education Scalar Types and Their Operations (continued) - Scalar Literals - An integer literal that fits in a machine word is a Fixnum - Other integer literals are Bignum objects - Any numeric literal with an embedded decimal point or a following exponent is a Float - All string literals are String objects - Single-quoted literals cannot include characters that are specified with escape sequences - Double-quoted literals can include escape sequences and embedded variables can be interpolated

Chapter 15 © 2014 by Pearson Education Scalar Types and Their Operations (continued) - Variables - A local variable is neither a class nor an instance variable - Names of local variables begin with lowercase letters and are case sensitive - Variables embedded in double-quoted literal strings are interpolated if they appear in braces and are preceded by a pound sign ( # ) - Expressions can also be embedded in braces in double-quoted literals - Variables do not have types—they are not declared - Assignment statement assign only object addresses - Numeric Operators - Arithmetic operators are like those of other languages, except Ruby has no ++ or -- - Division of integer objects is integer division

Chapter 15 © 2014 by Pearson Education Scalar Types and Their Operations (continued) - Numeric Operators (continued) - Any operation on Bignum objects that produces a result that fits in a Fixnum coerces it to a Fixnum - Any operation on Fixnum objects that produces a result that is too large coerces it to a Bignum - The Math module has methods for trig and transcendental functions e.g., Math.sin(x) - Interactive Ruby - irb is an interactive interpreter for Ruby - Shorten the prompt with conf.prompt_i = ">>" - String Methods - Some can be used as infix binary operators - Catenation is +, which can be infix - Append is <<, which can be infix

Chapter 15 © 2014 by Pearson Education Scalar Types and Their Operations (continued) - String Methods (continued) - Remember how assignment works! > > mystr = "Wow!" => "Wow!" >> yourstr = mystr => "Wow!" >> mystr = "What?" => "What?" >> yourstr => "Wow!" - If you want to change the value of the location that is referenced by a variable, use replace >> mystr.replace("Oh boy!") => "Oh boy!" - More String methods: capitalizestrip choplstrip chomprstrip upcasereverse downcaseswapcase

Chapter 15 © 2014 by Pearson Education Scalar Types and Their Operations (continued) - String Methods (continued) - The bang or mutator methods – add an ! - Strings can be indexed – str[3] - Substrings can be referenced – str[3, 5] - Specific characters of a string can be assigned with []= – str[2, 3] = "gg" - The == operator tests for equality of the objects - To test whether two variables reference the same object, use the equal? method - The eql? method tests whether the receiver object and the parameter have the same type and the same value - For ordering, use the operator; it returns 0, 1, or -1 - The * operator takes a string and a numeric expression—it replicates the string

Chapter 15 © 2014 by Pearson Education Simple Input and Output - Screen Output - puts takes a string literal as its operand - Implicitly attaches a newline - Use print if you don’t want the newline - sprintf is also available for conversions to string - Keyboard Input - The gets method gets a line of input from the keyboard and returns it, including the newline (returns nil if it gets EOF) (UNIX: EOF is Ctrl-D; Windows: EOF is Ctrl-Z) name = gets name = gets.chomp - If the input is a number, it must be converted with either to_i or to_f age = gets.to_i  SHOW quadeval.rb - Running a Ruby script ruby [flags] filename -c flag is compile only; -w flag is for warnings

Chapter 15 © 2014 by Pearson Education Control Statements - Control Expressions - true, false, nil (false), variables, relational expressions, or compound expressions - If it is a variable, it is true if its value is anything except nil - Relational operators: usual six (like C and Java) plus, eql?, and equal? - Two sets of Boolean operators: - Higher precedence: &&, ||, ! - Lower precedence: and, or, not - Operator precedence and associativity: - See Table Selection Statements if control_expression statement_sequence elsif control_expression statement_sequence... else statement_sequence end

Chapter 15 © 2014 by Pearson Education Control Statements (continued) - Selection Statements - unless is inverse of if - Two kinds of multiple selection constructs case expression when value then statement_sequence when value then statement_sequence … [ else statement_sequence] end - The values could be expressions, ranges (e.g., (1..10) ), class names, or regular expressions

Chapter 15 © 2014 by Pearson Education Control Statements (continued) - Semantics of the case statement: 1. There is an implicit break at the end of every selectable segment 2. The value of the expression is compared with the when values, top to bottom, until a match is found 3. A different operator, ===, is used for the comparisons. If the value is a class name, it is a match if its class is the same as that of the expression or one of its superclasses; if the value is a regular expression, === is a simple pattern match case in_val when -1 then neg_count += 1 when 0 then zero_count += 1 when 1 then pos_count += 1 else puts "Error – in_val is out of range" end

Chapter 15 © 2014 by Pearson Education Control Statements (continued) - Second form of multiple selection statement, which is actually an expression case when Boolean_expression then expression... when Boolean_expression then expression else expression end - The value of the whole expression is the value of the expression associated with the first true Boolean expression leap = case when year % 400 == 0 then true when year % 100 == 0 then false else year % 4 == 0 end - Logical pretest loop while control_expression loop body end - until has the same syntax, but opposite control

Chapter 15 © 2014 by Pearson Education Control Statements (continued) - Unconditional Loop loop body - The body optionally begins with begin and always ends with end - The break statement - Control goes to the first statement after the body - The next statement - Control goes to the first statement in the body - Ruby does not have a C-style for statement - Iterators are used instead - later

Chapter 15 © 2014 by Pearson Education Fundamentals of Arrays - Differences between Ruby arrays and those of other common languages: 1. Length is dynamic 2. An array can store different kinds of data - Array Creation 1. Send new to the Array class list1 = Array.new(100) - All elements reference nil list2 = Array.new(5, "Ho") - list 2 is [ "Ho", "Ho", "Ho", "Ho", "Ho"] 2. Assign a list literal to a variable list2 = [2, 4, , "Fred", [] ] - All array subscripts are integers and the first subscript is always zero - The length of an array is returned by length

Chapter 15 © 2014 by Pearson Education Fundamentals of Arrays (continued) - The for - in Statement for value in list sum += value end - The value variable takes on the values of the elements of list (not references to the values) - irb ’s response to a for construct is to return an array of the values taken on by the value variable - The list could be an array literal - Methods for Arrays and Lists - Adding and deleting the end elements - unshift, shift, push, pop - The concat method - Takes one or more parameters, which are pushed onto the end of the array - The reverse method - Does what its name implies

Chapter 15 © 2014 by Pearson Education Fundamentals of Arrays (continued) - Methods for Arrays and Lists (continued) - The include? predicate method - Searches the array for the given element - The sort method - For arrays of a single element type - Works for any type elements for which it has a comparison operation - Returns a new array; does not affect the array object to which it is sent  SHOW process_names.rb

Chapter 15 © 2014 by Pearson Education Hashes - a.k.a. Associative Arrays - Two fundamental differences between arrays and hashes: 1. Arrays use numeric subscripts; hashes use string values 2. Elements of arrays are ordered and are stored in contiguous memory; elements of hashes are not - Hash Creation 1. Send new to the Hash class my_hash = Hash.new 2. Assign a hash literal to a variable ages = ("Mike" => 14, "Mary" => 12) - Element references – through subscripting ages["Mary"] - Element are added by assignment ages["Fred"] = 9

Chapter 15 © 2014 by Pearson Education Hashes (continued) - Element removal ages.delete("Mike") - Hash deletion ages = () or ages.clear - Testing for the presence of a particular element ages.has_key?("Scooter") - Extracting the keys or values ages.keys ages.values

Chapter 15 © 2014 by Pearson Education Methods - All Ruby subprograms are methods, but they can be defined outside classes def method_name[ ( formal_parameters ) ] statement_sequence end - When a method is called from outside the class in which it is defined, it must be called through an object of that class - When a method is called without an object reference, the default object is self - When a method is defined outside any class, it is called without an object reference - Method names must begin with lowercase letters - The parentheses around the formal parameters are optional - Neither the types of the formal parameters nor that of the return type is given - If the caller uses the returned value of the method, the call is in the place of an operand in an expression

Chapter 15 © 2014 by Pearson Education Methods (continued) - If the caller does not use the returned value, the method is called with a standalone statement - The return statement is often used to specify the return value - If a return is not executed as the last statement of the method, the value returned is that of the last expression evaluated in the method - Local Variables - Local variables in methods are either formal parameters or variables created in the method - A local variable hides a global variable with the same name - The names of local variables must begin with either a lowercase letter or an underscore - The lifetime of a local variable is from the time it is created until execution of the method is completed

Chapter 15 © 2014 by Pearson Education Methods (continued) - Parameters - Formal parameters that correspond to scalar actual parameters are local references to new objects that are initialized to the values of the corresponding actual parameters - Actual parameters that are arrays or hashes are in effect passed by reference  SHOW median method - If a method has only normal parameters, the number of actual parameters must match the number of formal parameters - The normal scalar parameters in a method can be followed by an asterisk parameter, which is a reference to an array, which accepts any number of parameters, including none - Formal parameters can have default values - Keyword parameters can be implemented using hash literals as actual parameters - If the hash literal follows all normal scalar parameters and precedes any array or block parameters, the braces can be omitted find(age, {'first' => 'Davy', 'last' => 'Jones'})

Chapter 15 © 2014 by Pearson Education Methods (continued) - Parameters (continued) - Symbols are created by preceding an unquoted string with a colon - A symbol made from a variable’s name can be thought of as being that variable’s name - Does not refer to the variable’s value—it refers to its name - A symbol is not related to any particular instance of the variable - All symbols are instances of the Symbol class - Symbols can be used to specify the keys in hash literals used as actual parameters find(age, :first => 'Davy', :last => 'Jones')

Chapter 15 © 2014 by Pearson Education Classes class class_name … end - Class names must begin with uppercase letters - The names of instance variables must begin with at signs ) - Each class implicitly has a constructor, new, which is called to create an instance - The new constructor calls the class initializer - A class may have a single initializer, initialize - Initializes the instance variables - Parameters for initialize are passed to new  SHOW Stack2_class.rb - Classes are dynamic – subsequent definitions can include new members; methods can be removed with remove_method in subsequent definitions - Access Control - All instance data has private access by default, and it cannot be changed

Chapter 15 © 2014 by Pearson Education Classes (continued) - Access Control (continued) - If needed, external access to instance variables is provided with getters and setters class My_class # Constructor def = = 2 end # A getter def end # A setter def = my_one end - Note the ″=″ in the setter name - When an instance variable is referenced inside the class, is included in the name; when referenced outside the class, it is excluded - Shortcuts for getters and setters attr_reader :one, :two attr_writer :one

Chapter 15 © 2014 by Pearson Education Classes (continued) - Access Control (continued) - Method access control: public, private, and protected - Public and protected are as in Java, etc. - Private means the method cannot be called through an object reference - There are two ways to specify access 1. Call the access function without parameters – resets the default (which is public) 2. Following all method definitions in a class, call the access function, passing the method names as symbols private :meth7, … - Access control of methods is dynamic - Subsequent class definitions can specify different access levels - Class variables are private to the class and its instances

Chapter 15 © 2014 by Pearson Education Classes (continued) - Inheritance class My_Subclass < Base_class - Modules - A way to collect related methods into an encapsulation - Access to a module is with include include Math - The methods in a module are mixed into those of the class that includes it – mixins - Provides the benefits of multiple inheritance

Chapter 15 © 2014 by Pearson Education Blocks and Iterators - A block is a segment of code, delimited by either braces or do and end - By itself, a block does nothing - Blocks can be sent to methods by attaching them to calls - This construct is used to build iterators - Built-in Iterators times – blocks are sent to number objects to build simple counting loops 5.times {puts "hey!"} - Blocks can have parameters; they appear at the beginning of the block in vertical bars ( | ) each – blocks are sent to array objects; the block is applied to each element of the array list.each {|value| puts value} - If each is used on a hash, two block parameters are required (key and value)

Chapter 15 © 2014 by Pearson Education Code Blocks and Iterators (continued) upto – blocks are sent to number objects, including a parameter for the last value 5.upto(8) {|value| puts value} step – blocks are sent to number objects, including two parameters for the last value and a step size 0.step(6, 2) {|value| puts value} collect – sent to an array, like each, but the block constructs and returns a new array list.collect {|value| value -= 5} - The mutator version of this is often useful – collect! - Blocks can be passed as parameters - Example – see Chapter 16

Chapter 15 © 2014 by Pearson Education Code Blocks and Iterators (continued) - User-defined blocks - Blocks are called in methods with yield, which can include parameters to the block def get_name puts "Your name:" name = gets yield(name) end get_name {|name| puts "Hello, " + name}

Chapter 15 © 2014 by Pearson Education Pattern Matching - Patterns are placed between slashes - Use the =~ operator between a string and a pattern name = "Freddie" name =~ /d/  SHOW word_table.rb - Remembering matches $1, $2, … have the matches from the first parenthesized subpatterns - Substitutions - Ruby has four methods of the String class for string substitutions str.sub( pattern, replacement ) str.gsub( pattern, replacement ) - There are also mutator versions - The i modifier can follow the pattern