Overview of the Ruby Language. By Ron Haley

Similar documents
CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341


IT 374 C# and Applications/ IT695 C# Data Structures

Data Structures (list, dictionary, tuples, sets, strings)

Java Bytecode (binary file)

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Programming in Visual Basic with Microsoft Visual Studio 2010

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

Programming Paradigms

String Computation Program

Chapter 6 Introduction to Defining Classes

Ruby: Introduction, Basics

Chapter 4 Defining Classes I

CSE 341, Autumn 2015, Ruby Introduction Summary

Introduction to Programming Using Java (98-388)

The PCAT Programming Language Reference Manual

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CS 5142 Scripting Languages

A A B U n i v e r s i t y

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Absolute C++ Walter Savitch

Working with JavaScript

Ruby: Introduction, Basics

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang

CSE 413 Programming Languages & Implementation. Hal Perkins Winter 2019 Ruby Containers, Blocks, and Procs

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Cpt S 122 Data Structures. Introduction to C++ Part II

Installation Download and installation instructions can be found at

What is Ruby? CSc 372. Comparative Programming Languages. 27 : Ruby Introduction. Department of Computer Science University of Arizona

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 360 Programming Languages Interpreters

Index COPYRIGHTED MATERIAL

15.1 Origins and Uses of Ruby

Ruby: Introduction, Basics

Your First Ruby Script

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Pace University. Fundamental Concepts of CS121 1

Java 8 Programming for OO Experienced Developers

Table of Contents EVALUATION COPY

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS260 Intro to Java & Android 03.Java Language Basics

Java Programming Training for Experienced Programmers (5 Days)

Maciej Sobieraj. Lecture 1

Web Application Expectations

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

CPS122 Lecture: From Python to Java

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Java+- Language Reference Manual

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

A LISP Interpreter in ML

4. Structure of a C++ program

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

CERTIFICATE IN WEB PROGRAMMING

Problem Solving with C++

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

Extending Jython. with SIM, SPARQL and SQL

JavaScript CS 4640 Programming Languages for Web Applications

The SPL Programming Language Reference Manual

Fundamentals of Programming. Lecture 3: Introduction to C Programming

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

Basic Syntax - First Program 1

SCHEME AND CALCULATOR 5b

BoredGames Language Reference Manual A Language for Board Games. Brandon Kessler (bpk2107) and Kristen Wise (kew2132)

Sprite an animation manipulation language Language Reference Manual

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

CS 231 Data Structures and Algorithms, Fall 2016

A Small Interpreted Language

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Unit E Step-by-Step: Programming with Python

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

An introduction to Scheme

Lesson 1: Writing Your First JavaScript

Computer Programming C++ Classes and Objects 6 th Lecture

Fundamental of Programming (C)

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Smalltalk: developed at Xerox Palo Alto Research Center by the Learning Research Group in the 1970 s (Smalltalk-72, Smalltalk-76, Smalltalk-80)

COMS 469: Interactive Media II

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS 390 Software Engineering Lecture 6 Ruby

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Chapter 2, Part I Introduction to C Programming

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

JME Language Reference Manual

YOLOP Language Reference Manual

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Fast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3. Course Code: GK1965. Overview

9.2 Linux Essentials Exam Objectives

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

CS201 - Introduction to Programming Glossary By

Language Reference Manual

Transcription:

Overview of the Ruby Language By Ron Haley

Outline Ruby About Ruby Installation Basics Ruby Conventions Arrays and Hashes Symbols Control Structures Regular Expressions Class vs. Module Blocks, Procs, and Lambdas

About Ruby Ruby is a genuine object-oriented language In Ruby, everything is an object, everything you manipulate is an object, and the results of those manipulations are themselves objects In many languages, numbers and other primitive types are not objects. In Ruby, methods and instance variables are given to all of its types. Ruby is flexible, all objects can be modified at runtime. Ruby has exception handling. Ruby features a garbage collector for all Ruby objects.

Installation You can download the source code (https://www.ruby-lang.org/en/ downloads/) and compile it on your own. On Linux/UNIX systems you can use the package management system. Ex. sudo apt-get install ruby-full On Windows you have to use RubyInstaller. *using Windows for development is not recommended. On OS X machines use third-party versioning tools like rvm or rbenv. *preferred way

Installation Cont. rvm (ruby version manager) https://rvm.io/ RVM is a command-line tool which allows you to easily install, manage, and work with multiple ruby environments from interpreters to sets of gems. rbenv https://github.com/sstephenson/rbenv rbenv allows you to pick a Ruby version for your application and guarantees that your development environment matches production you typically install the ruby-build (https://github.com/ sstephenson/ruby-build#readme) plugin to use along with rebind which will provide an install command that will download and compile specific versions of Ruby for you. Ex. rbenv install 2.2.3

Installation Cont. Ruby provides a tool (shell) to interactively execute ruby expressions read from the standard input. irb (interactive ruby) is a command you can use in your shell to open up a Ruby interpreter. Default Ruby interpreter. pry (https://github.com/pry/pry) is an irb alternative that provides some advanced features like: source code browsing, document browsing, and runtime invocation which allows pry to be used as a developers console or debugger which is very helpful in a Ruby on Rails project. *Rails comes with a default console and debugger but can use pry as alternative. there are many plugins for pry that can assist you in development. For example you can install a plugin to allow developer to use breakpoints in code for debugging purposes.

Basics Example: The code before period is called the receiver, the name after the period is the method being invoked. Note: The main difference between Ruby and a language like Java can be shown by finding the absolute value of a number. Example:

Basics Cont. Example: Observations: You do not need semicolons as long as the statement is on a separate line. Indentation is not important but is recommended for readability.

Basics Cont. methods that end with! mean that the method will modify the object it is called on. methods are defined by the keyword def and followed by the method name and the method parameters between parentheses. Ruby does not use braces to delimit bodies of compound statements, instead you finish a statement with the keyword end. Comments start with # Ex. # This is a single line comment in Ruby! Block comments use =begin and =end to wrap comment Note: =begin and =end must not be indented.

Basics Cont. String objects string literal: are sequences of characters between single or double quotation marks. You can use either but there are some differences between the amount of processing Ruby does while constructing the literal. Single quotes: Ruby does little processing, what you type into the string literal becomes the string s value. Double quotes: Ruby first looks for substitutions ( \n, \t, etc.) and replaces them with the binary value. Next, Ruby performs any expression interpolations ( any sequences of #{expression} within the string are replaced by the value of expression).

Basics Cont. Examples of expression interpolation with double quoted strings: The second example shows that complex expressions are allowed in the #{ } construct.

Basics Cont. Class variables vs. Instance variables A class variable is shared among all objects of a class, and it is also accessible to the class methods. There is only one copy of a particular class variable for a given class. Class variable names start with two ``at'' signs, @@var_name Class variables must be initialized before they are used this is often just a simple assignment in the body of the class definition Class variables are private to a class and its instances. If you want to make them accessible to the outside world, you'll need to write an accessor method. (setter/getter)

Basics Cont. Class methods provide work without being tied to any particular object. Class methods are distinguished from instance methods by their definition. Class methods are defined by placing the class name and a period in front of the method name. Example of the difference between instance method and class method: *Note: the method signatures are using the wrong naming convention. Also, common practice would be to use self instead of the class name. Ex. def self.my_method

Basics Cont. Instance methods only work with an instance; therefore, you have to create a new instance to use them (MyClass.new). We cannot call instance method with respect to the class.

Basics Cont. Instance variables begin with an at sign (@var_name) and can be referenced only within class methods. They differ from local variables in that they don't exist within any particular scope. Instance variables live within a class instance, so as long as that instance stays alive, so will the instance variables. Instance variables can be referenced in any method of that class. All methods of a class use the same instance variable table, as opposed to local variables where each method will have a different variable table. Instance variables should be used when they represent the state of the object

Ruby Conventions Ruby naming conventions Local Variable Instance Variable Class Variable Global Variable Class Name Constant Name name @name @@name $test String PI first_name @name_1 @@symtab $MERCHANT ActiveRecord MILE_PER_H OUR y_axis @Y @@A $_ MyClassName DEBUG now123 @_ @@y_axis $now123 _22 @name1 @@ONE $GLOBAL

Arrays and Hashes Arrays and hashes are indexed collections Both store collections of objects that are accessible by using a key. With arrays, the key is an integer; hashes support any object as the key. Both containers grow as needed to hold new elements. Any array or hash can hold objects of different types. Arrays can be created and initialized by using an array literal (a set of elements between square brackets) Like most languages, you can access individual elements of an array object by supplying an index between square brackets. Array indexes start at zero.

Arrays and Hashes Cont. Example:

Arrays and Hashes Cont. Tip: creating arrays can become a pain when all the objects require quotes and commas, Ruby provides a formatting shortcut. Example: or

Arrays and Hashes Cont. A hash literal uses braces rather than square brackets. The literal must supply two objects for every entry: one for the key, the other for the value. The key and value are normally separated by => the object to the left is the key and the object to the right is the value. Keys in a particular hash must be unique, the keys and values in the hash can be arbitrary objects (you can have hashes where the values are arrays, other hashes, etc) Hashes are indexed using the same square bracket notation as arrays.

Arrays and Hashes Cont. Example: Create and initialize a hash Console input/output

Arrays and Hashes Cont. Hashes by default return nil when indexed by a key it doesn t contain. Ruby allows the ability to set a default value when you create a new one. Example:

Symbols Symbols in Ruby are constant names that you don t have to predeclare and that are guaranteed to be unique. A symbol literal starts with a colon and is followed by some kind of name :constant_name Symbols can are similar to constants in other languages. For example, consider: In Ruby you would write this:

Symbols Cont. There is no need to assign the symbol a value since Ruby does that for you Ruby guarantees that no matter where the symbol appears in your program, a particular symbol will have the same value. Therefore, you can define the walk method used in previous example as:

Symbols Cont. Symbols are often used in hashes; therefore, we could create our previous hash like this: Symbols are so commonly used in hashes that Ruby 1.9 introduced a new syntax, again the previous example can be re-written as:

Control Structures The Ruby language has all the control structures (if statements, while loops) as other languages like java and C. The main difference is the lack of braces surrounding the bodies of these structures. Ruby uses the keyword end to signify the end of the body of a control structure. Example:

Control Structures Cont. Since most statements in Ruby return a value, they make good candidates for conditions. For example, the method gets returns the next line from standard input stream or nil when the end of the file is reached. Because nil is treated as false in Ruby for condition statements, you could write something like this to read the lines of a file.

Control Structures Cont. Statement modifiers are a shortcut if the body of a control structure is just a single expression. Simply write the the expression followed by the if or while condition. Example these statements: can be re-written as:

Regular Expressions Like other scripting languages, Ruby has built in support for regular expressions rather than being tacked on through a library interface. A regular expression is just a way of specifying a pattern of characters to be matched in a string. Regular expressions in Ruby are created by writing a pattern between slash characters /pattern/ Regular expressions are objects in Ruby; therefore, they can be manipulated.

Regular Expressions Cont. /Ruby Rails/ is a pattern that matches a string containing the text Ruby or the text Rails. The match operator =~ can be used to match a string against a regular expression. If the pattern is found in the string, =~ returns its starting position; otherwise, it returns nil. Example:

Class Class names are CamelCase'd and Capitalized the initialize method is the class constructor and is optional when defining a class.

Class Cont. Accessors: You can define read/write permissions on class variables. attr_accessor gives access to set and read a variable by providing helper methods.

Class Cont. You could also use the read/write accessors to achieve the same result as in prior example.

Modules Can be used for name spacing. Can also consist of a collection of methods that can be mixed into a class or can be used to extend a class.

Polymorphism Polymorphism: - the provision of a single interface to entities of different types. In Ruby, it means being able to send the same message to different objects and get different results. Inheritance: one method to achieve polymorphism is through inheritance as can be seen in this example of the template design pattern.

Polymorphism Cont. Duck Typing (runtime polymorphism): Duck Typing refers to the tendency of Ruby to be less concerned with the class of an object and more concerned with what methods can be called on it and what operations can be performed on it. You should treat objects according to the methods they define rather than the classes from which they inherit or the modules they include

Blocks, Procs, and Lambda Blocks, Procedures (Procs), and Lambdas; referred to as closures, anonymous functions, or function literals. It is an important aspect of the Ruby language. Since Ruby handles closures in a unique way and the fact that there are multiple ways of using closures each of which has its own benefit; this is probably the most misunderstood feature Ruby has to offer. A function that is defined without being bound to an identifier (not named). Local instance variables are accessible inside a closure. Blocks and Procs act like drop-in code snippets, while lambdas and Methods act just like methods.

Blocks Blocks or code blocks; are chunks of code between braces or the keywords do-end that you can associate with method invocations as if they were parameters. Can be passed to any function (and ignored). Code blocks may appear only in the source adjacent to a method call; the block is written starting on the same line as the method call's last parameter (or the closing parenthesis of the parameter list). The code in the block is not executed at the time it is encountered. Instead, Ruby remembers the context in which the block appears (the local variables, the current object, and so on) and then enters the method.

Blocks Cont. The Ruby standard is to use braces for single-line blocks and doend for multi-line blocks. Keep in mind that the braces syntax has a higher precedence than the do..end syntax. Inside a method, you can call a Ruby block using the yield keyword with a value. You can provide parameters to the call to yield: these will be passed to the block. Within the block, you list the names of the arguments to receive the parameters between vertical bars ( ). The do and end identify a block of code that will be executed for each item.

Blocks Cont. Use blocks when: Your method is breaking an object down into smaller pieces, and you want to let your users interact with these pieces. You want to run multiple expressions atomically, like a database migration. Example of a simple block:

Previous example re-written: Blocks Cont.

Procs To have many different blocks at our disposal and use them multiple times would require passing the same block again and would require us to repeat ourself. Ruby can handled this cleanly by saving reusable code as an object itself. This reusable code is called a Proc (short for procedure). The only difference between blocks and Procs is that a block is a Proc that cannot be saved, and as such, is a one time use solution. Note: block is invoked using yield and proc is invoked using call Once bound, the code may be called in different contexts and still access those variables. Passing Procs is no different then passing any other data type, as

Procs Cont. Use Procs over blocks when: You want to reuse a block of code multiple times. Your method will have one or more callbacks. Previous example as a Proc:

Lambdas Lambdas behave the same as Procs. However, there are two subtle differences. The first difference is that, unlike Procs, lambdas check the number of arguments passed. The second difference is that lambdas have diminutive returns. This means that while a Proc return will stop a method and return the value provided, lambdas will return their value to the method and let the method continue on.

Lambdas Cont. Previous Array iterate example as a Lambda:

References Rails Api: http://api.rubyonrails.org/ Rails Guides: http://guides.rubyonrails.org/ Ruby Api: http:// ruby-doc.org/core-2.2.3/