CS 5142 Scripting Languages

Similar documents
Ruby: Introduction, Basics

CSCI-GA Scripting Languages

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework

CSE 341, Autumn 2015, Ruby Introduction Summary

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

Ruby: Introduction, Basics

Ruby: Introduction, Basics

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

Ruby. Mooly Sagiv. Most slides taken from Dan Grossman

CSE 341: Programming Languages

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

Overview of the Ruby Language. By Ron Haley

Ruby on Rails TKK, Otto Hilska

15.1 Origins and Uses of Ruby

Programming Paradigms

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

Introduction to Ruby. SWEN-250 Personal Software Engineering

Ruby Topic Maps. Introduction to Ruby. Benjamin Bock.

CSCI-GA Scripting Languages

Installation Download and installation instructions can be found at

Your First Ruby Script

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Introduction CMSC 330: Organization of Programming Languages. Books on Ruby. Applications of Scripting Languages

Ruby on Rails for PHP and Java Developers

Ruby Primer and Review for Developers

CGS 3066: Spring 2015 JavaScript Reference

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

Why Discuss JavaScript? CS312: Programming Languages. Lecture 21: JavaScript. JavaScript Target. What s a Scripting Language?

CS312: Programming Languages. Lecture 21: JavaScript

Scala : an LLVM-targeted Scala compiler

CSE341: Programming Languages Spring 2017 Unit 7 Summary Dan Grossman, University of Washington

Introduction to Programming Using Java (98-388)

Babu Madhav Institute of Information Technology, UTU 2015

CSCI-GA Scripting Languages

G Programming Languages - Fall 2012

The Pyth Language. Administrivia

CS 390 Software Engineering Lecture 6 Ruby

1. Introduction. 2. Scalar Data

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

JewelScript Reference Manual

Lecture 1. Basic Ruby 1 / 61

Scripting Languages Perl Basics. Course: Hebrew University

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

DaMPL. Language Reference Manual. Henrique Grando

FRAC: Language Reference Manual

Decaf Language Reference Manual


A Tour of Ruby.... for Java programmers

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

CEU s (Continuing Education Units) 12 Hours (i.e. Mon Thurs 5 9PM or Sat Sun 8AM 5PM)

CSE341: Programming Languages Lecture 20 Arrays and Such, Blocks and Procs, Inheritance and Overriding. Dan Grossman Spring 2017

G Programming Languages - Fall 2012

Introducing Wybe a language for everyone

Introduction to Ruby, part I

Key Differences Between Python and Java

CS260 Intro to Java & Android 03.Java Language Basics

Introduction to JavaScript p. 1 JavaScript Myths p. 2 Versions of JavaScript p. 2 Client-Side JavaScript p. 3 JavaScript in Other Contexts p.

RUBY OPERATORS. Ruby Arithmetic Operators: Ruby Comparison Operators:

JavaScript: Sort of a Big Deal,

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

CMSC 330: Organization of Programming Languages

Decaf Language Reference

JavaScript. History. Adding JavaScript to a page. CS144: Web Applications

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

Outline. CS3157: Advanced Programming. Feedback from last class. Last plug

Common LISP Tutorial 1 (Basic)

Fall 2017 CISC124 9/16/2017

Control Structures. Important Semantic Difference

RUBY VARIABLES, CONSTANTS AND LITERALS

COMS 3101 Programming Languages: Perl. Lecture 5

CS /534 Compiler Construction University of Massachusetts Lowell. NOTHING: A Language for Practice Implementation

Adding Static Typing to Ruby

Coral Programming Language Reference Manual

ENGR 101 Engineering Design Workshop

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Spoke. Language Reference Manual* CS4118 PROGRAMMING LANGUAGES AND TRANSLATORS. William Yang Wang, Chia-che Tsai, Zhou Yu, Xin Chen 2010/11/03

CSE 341: Programming Languages. Section AC with Nate Yazdani

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

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

Node.js Training JavaScript. Richard richardrodger.com

COMP284 Scripting Languages Lecture 2: Perl (Part 1) Handouts

Lexical Considerations

Combining Static and Dynamic Typing in Ruby: Two Approaches. Jeff Foster University of Maryland, College Park

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

Index COPYRIGHTED MATERIAL

Chapter 1. Fundamentals of Higher Order Programming

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

CS558 Programming Languages

Semantic Processing. Semantic Errors. Semantics - Part 1. Semantics - Part 1

And Parallelism. Parallelism in Prolog. OR Parallelism

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

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

Scala. Fernando Medeiros Tomás Paim

COP4020 Programming Assignment 1 - Spring 2011

CS 349 / SE 382 Scripting. Professor Michael Terry March 18, 2009

Simple Java Reference

Client-Side Web Technologies. JavaScript Part I

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

Transcription:

CS 5142 Scripting Languages 10/25/2012 Ruby 1

Outline Ruby Martin Hirzel 2

About Ruby Invented 1995 by Yokihiro Matz Matsumoto Influenced by SmallTalk Everything is an object (even e.g., integers) Blocks and user-defined control constructs Influenced by Perl RegExp match =~ / /, default variable $_ Common use: RoR (Ruby on Rails) framework for web programming 3

How to Write + Run Code One-liner: ruby e 'command' Run script from file: ruby file.rb Debugger: ruby -rdebug file.rb Check syntax only: ruby -c file.rb Read-eval-print loop (interactive Ruby): irb Run stand-alone: #!/usr/bin/env ruby 4

Example #!/usr/bin/env ruby $cup2g = { 'flour'=>110, 'sugar'=>225, 'butter'=>225 } $volume = { 'cup'=>1, 'tbsp'=>16, 'tsp'=>48, 'ml'=>236 } $weight = { 'lb'=>1, 'oz'=>16, 'g'=>453 } while gets $_ =~ /([0-9.]+) (\w+) (\w+)/ $qty, $unit, $ing = [$1, $2, $3] if $cup2g.key?($ing) and $volume.key?($unit) $qty = $qty.to_f * $cup2g[$ing] / $volume[$unit] $unit = 'g' elsif $volume.key? $unit $qty = $qty.to_f * $volume['ml'] / $volume[$unit] $unit = 'ml' elsif $weight.key? $unit $qty = $qty.to_f * $weight['g'] / $weight[$unit] $unit = 'g' end puts "qty #{$qty.to_i}, unit #{$unit}, ing #{$ing}\n" end 5

Lexical Peculiarities Case sensitive Single-line comment: # Multi-line comment: =begin =end Line break ends statement, optional semicolon (;) Sigils indicate scope, not type Heredocs Expression interpolation: " #{ } " Literals: "s", 's', true, nil, RegExp / /, Array [1,2,3], Hash {'x'=>1,'y'=>2}, Symbol :foo 6

Types mixin Object Kernel Integer Numeric Float IO Array File Hash String Symbol (other classes) Fixnum Bignum 7

Variable Declarations There are no explicit variable declarations Reading an undefined variable is an error Scope First letter Local variable or method Object variable (private) Class variable (static) Global variable $ Constant; convention: MixedCase = class name ALL_CAPS = value Lowercase or _ @ @@ Uppercase 8

Type Conversions Class Value Boolean Number String FalseClass false Identity Error Error TrueClass true Fixnum String 0 Other "" "0" Other true Identity Error true Error Identity NilClass nil false Error Error Array Empty Other true Error Error Object true Error Error Explicit conversions: x.to_i(), x.to_f(), x.to_s(), 9

Concepts Duck Typing If it walks like a duck and quacks like a duck, it s a duck. If a value supports the operations for a certain type, Ruby treats it as that type. This is normal for dynamic typing, but unusual for objectoriented languages. 10

Input and Output Output: p(), print(), printf(), puts() Input: gets(), readline(), readlines() Like Perl, Ruby has implicit variables E.g., $1, $2, are groups from pattern match, and $_ is result of gets or readline Many operators are actually methods E.g., + and - are methods on number objects, and =~ is method on string objects for RegExp match 11

Operators :: 2 Scope resolution [],[]= 2 Read from array, write to array ** 2 Exponentiation +, -,!, ~ 1 Positive, negative, negation, complement *, /, % 2 Multiplicative +, - 2 Additive <<, >> 2 Shifting &,, ^ 2 Bitwise (not all same precedence) >, >=, <, <= 2 Comparison <=>, ==, ===,!=, =~,!~ 2 Identity, pattern matching &&, 2 Logical (not all same precedence)..,... 2 Range inclusive, exclusive?: 3 Conditional =, +=, -=, 2 Assignment not, and, or Logical (not all same precedence) defined? 1 (no precedence) 12

Control Statements Conditional Loops Fixed Indefinite Unstructured control Exception handling Modifiers if expr then elsif else end unless expr then elsif else end case expr when expr: else end for var in expr do end while expr do end until expr do end break, redo, next, retry return [expr] yield begin rescue Cls ensure end raise [Cls] stmt [if unless while until] expr 13

Alternative Control Syntax if x==5: puts 'five' end if x==5 then puts 'five' end if x==5 puts 'five' end Less variation for other control statements, e.g., while with do or newline for with do or newline 14

Writing Subroutines Declaration: def id [(arg*)] end Explicit return, or value of last expression in body Convention: when id ends with?, return boolean; =, set field;!, make destructive update yield executes block parameter; when block terminates, resume current subroutine after yield Arguments: arg ::= [*]id Splat (*) gives variable number of arguments Deleting a subroutine: undef id Duplicating a subroutine: alias id 1 id 2 Block (parameter closure): block ::= { arg* } Procs (first-class closure): (proc lambda) block 15

#!/usr/bin/env ruby # 1 def myiterator(x) # 2 x += 3 # 3 yield x # 4 x += 3 # 5 yield x # 6 x += 3 # 7 yield x # 8 end # 9 $i = 0 #10 myiterator(1){ y #11 $i += 1 #12 puts "call #{$i}:" #13 puts y #14 } #15 puts 'done' #16 Iterators Caller Iterator Block 10 11 16 return Many Ruby classes have iterator methods that take a block parameter. call 3 4 5 6 7 8 9 return return yield 4 yield 7 yield 10 return 12 13 14 12 13 14 12 13 14 16

Concepts Code Blocks as Parameters Code block = { arg* stmt*} syntax for anonymous function Similar to a lambda Can be passed as parameter to iterator method The code block is a closure (has access to caller s environment) Caller Iterator Block call call return return call return 17 Martin Hirzel 17

Using Objects a1 = Apple.new(150, "green") a2 = Apple.new(150, "green") a2.color= "red" puts a1.prepare("slice") + "\n" puts a2.prepare("squeeze") + "\n" Constructor calls Setter call Method calls 18

Defining Classes class Fruit def initialize(weight_) @weight = weight_ end def weight @weight end def weight= (value) @weight = value end def pluck "fruit(" + @weight + "g)" end def prepare(how) how + "d " + pluck end end Fruit @weight initialize() pluck() prepare() All fields are private, external use requires accessors (e.g., @weight, weight, weight=) Classes are open, can add additional fields+methods 19

Inheritance in Ruby class Fruit def initialize(weight_) @weight = weight_ end def weight @weight end def weight= (value) @weight = value end def pluck "fruit(" + @weight + "g)" end def prepare(how) how + "d " + pluck end end class Apple < Fruit def initialize(weight_, color_) @weight = weight_ @color = color_ end def color @color end def color= (value) @color = value end def pluck self.color + " apple" end end Fruit @weight initialize() pluck() prepare() Apple @weight @color initialize() pluck() prepare() 20

Scopes and Visibility Visibility of class members All instance variables are private Methods can be private, protected, or public Accessor generation class Fruit attr_accessor :weight def initialize(weight_) @weight = weight_ end def pluck "fruit(" + @weight + "g)" end def prepare(how) how + "d " + pluck end end Generates @weight field and weight/weight= methods Fruit @weight initialize() pluck() prepare() Martin Hirzel 21

Structure of a Ruby Application require file Module = like class, but can t be instantiated Class can include ( mix in ) one or more modules Members of mix-in module are copied into class Later definition with same name overrides earlier Module can inherit from other module, but not class Module can contain methods, classes, modules Module Kernel is mixed into class Object Top-level subroutines are private instance methods of the Kernel module Visible everywhere, can t call with explicit receiver 22

Arrays Initialization: $a=[1,2,3] With block: $a=array.new(10){ e 2*e} Indexing: $a[ ] Zero-based, contiguous, integers only Negative index counts from end Deleting: $a.clear(), $a.compact(), $a.delete_at(i) Lots of other methods 23

Hashes Initialization: $h = {'lb'=>1,'oz'=>16,'g'=>453} Indexing: $h['lb'] Can use any object as key, not just strings Deleting: $h.clear(), $h.delete(k) Lots of other methods Can have a default closure : return value for keys not explicitly stored 24

Reference Ruby Documentation http://www.ruby-lang.org http://www.rubyonrails.org Book: The Ruby Programming Language. David Flanagan, Yokihiro Matsumoto. O Reilly, 2008 25

Soap-Box Evaluating Ruby Strengths Rails Purely object oriented Perl-like =~ and default variables Weaknesses Less popular than Java and PHP Unusual syntax 26

Administrative No announcements. Today s lecture Ruby Last Slide Martin Hirzel 27