36
Scripting with Ruby What is a scripting language? What is Ruby?

Scripting with Ruby What is a scripting language? What is Ruby?

Embed Size (px)

Citation preview

Page 1: Scripting with Ruby What is a scripting language? What is Ruby?

Scripting with Ruby

What is a scripting language?

What is Ruby?

Page 2: Scripting with Ruby What is a scripting language? What is Ruby?

Scripting Languages

• Originally, a script was a file containing a sequence of commands that needed to be executed

• Control structures were added to make it possible to do more with scripts

Page 3: Scripting with Ruby What is a scripting language? What is Ruby?

Characteristics of Scripting Languages

• Generally interpreted

• Dynamic typing - no declarations

• Make text processing easy

• Often provide pattern matching for strings

• Provide file and directory manipulation

• Make it easy to do things quickly

Page 4: Scripting with Ruby What is a scripting language? What is Ruby?

Basic Scripting Languages

• Unix and Linux come with shell programs which are programmable – sh

– bash

– ksh

– csh

• DOS had BAT files

Page 5: Scripting with Ruby What is a scripting language? What is Ruby?

Scripting in Other Environments

• Even with a GUI operating system, it is still useful to be able to automate repetitive tasks– Windows still has bat files– Mac OS has AppleScript

• Some applications have a scripting language built into them– Microsoft applications have Visual Basic for

Applications (VBA)– Hypercard (Apple) had HyperTalk

Page 6: Scripting with Ruby What is a scripting language? What is Ruby?

Other Scripting Languages

• Other scripting languages were developed to provide increased capability– sed -- adapted from the UNIX ed editor in 1977 – AWK -- created by Ajo, Wienberger and Kernighan in

1977– Tcl -- an extensible scripting language written by John

Ousterhout in 1987– Perl -- created by Larry Wall in 1986– Python-- created in 1989 by Guido van Rossum– Ruby -- created in 1993 by Yukihiro Matsumoto

Page 7: Scripting with Ruby What is a scripting language? What is Ruby?

Scripting and the Web

• More recently, a number of scripting languages have been developed for use with web browsers– PHP

– JavaScript

– Active Scripting provided scripting for web pages built using the ASP framework

Page 8: Scripting with Ruby What is a scripting language? What is Ruby?

Scripting on onyx

• the shell languages• sed• awk• perl• python• ruby• tcl

• javascript

• php

Page 9: Scripting with Ruby What is a scripting language? What is Ruby?

History

• Written by Yukihiro “matz” Matsumoto• First released in 1995• Blend of Perl, Smalltalk, Eiffel, Ada and

Lisp

Page 10: Scripting with Ruby What is a scripting language? What is Ruby?

Ruby

• object-oriented– everything is an object

• interpreted• "syntax light"• variables are dynamically typed

– variables are references to objects

• supports single inheritance– mixins give some of benefits of multiple inheritance

Page 11: Scripting with Ruby What is a scripting language? What is Ruby?

Running a ruby program

• Run the interpreter by typing ruby prog.rb

• Make an executable script– The first line should be

#!/usr/bin/ruby

– Make the file executable and type its name to run itchmod +x prog.rb./prog.rb

• Use the irb command to get an interactive session

Page 12: Scripting with Ruby What is a scripting language? What is Ruby?

Basic Syntax

• Program is a sequence of definitions and statements

• No semicolons at end of statement– semicolons can separate statements on a single line

• Parentheses around method arguments are optional – unless ambiguous

• Comments start with a #

Page 13: Scripting with Ruby What is a scripting language? What is Ruby?

Naming

• Conventions– local variables, parameters and method names

start with lower case letter or underscore– class and module names and constants start

with an uppercase letter

• instance variables start with @• class variables start with @@• global variables start with $

Page 14: Scripting with Ruby What is a scripting language? What is Ruby?

Numbers in Ruby

• Numbers are objects– Integer– Fixnum– Bignum– Float– Complex

• Ruby distinguishes between integers and floating point types

• Usual operators plus exponentiation

• Math class has usual selection of methods

• Integers can have an arbitrary number of digits

Page 15: Scripting with Ruby What is a scripting language? What is Ruby?

Ranges• Ruby has a class that represents subranges

1..10'a'..'z'

• Can be used as conditions• Operations

– to_a converts range to array– include? tests for inclusion, also ===– min, max– each is iterator– reject is iterator that skips members based on some

condition

Page 16: Scripting with Ruby What is a scripting language? What is Ruby?

Representing Text

• A string is a sequence of characters– Original implementation was a simple array of

bytes– Now consists of an array of bytes with an

associated encoding

• No separate type for a single character

Page 17: Scripting with Ruby What is a scripting language? What is Ruby?

Strings• Literals can use either single or double

quotes– Variables can be interpolated in double-quoted

strings"name = #{name}"

– Escape characters are replaced in double-quoted strings

– Single quoted strings can escape only \ and '

• %q and %Q are alternate forms for single and double quoted strings

• Also, check out here documents

Page 18: Scripting with Ruby What is a scripting language? What is Ruby?

String Operations

• Strings can be concatenated with +– both operands must be strings

• << concatenates another type of object• * repeats the string a specified number of

times• == and === compare for equality• <==> is like compare to• [] indexes an element

Page 19: Scripting with Ruby What is a scripting language? What is Ruby?

String methods

• split, scan followed by optional regular expression tokenize string

• capitalize, capitalize!, downcase, downcase!

• include?

• index

• length

Page 20: Scripting with Ruby What is a scripting language? What is Ruby?

Regular Expressions

• Patterns enclosed between slashes/<pattern>/

• Operator =~ means matches (returns boolean)

• Uses perl syntax

Page 21: Scripting with Ruby What is a scripting language? What is Ruby?

Arrays

• Creating– create with literal

– Array.new creates an empty array

• Size can grow dynamically

• Slices can be retrieved and assigned

• Useful methods: concat, collect, delete, each, empty?, join, sort, dup

Page 22: Scripting with Ruby What is a scripting language? What is Ruby?

Hashes

• Creating– Use a literal

h = {'horse' => 'mammal', 'trout' => 'fish', 'frog' => 'amphibian'}

– Use newh2 = Hash.new

can specify value of missing element as argument to new

Page 23: Scripting with Ruby What is a scripting language? What is Ruby?

Hash Methods

• default returns the default value (nil by default); can also be set

• delete, delete_if remove elements• replace updates an element• each, each_key, each_value iterate through

the hash• length returns number of entries• has_key?, has_value?• sort (by key), dup, …

Page 24: Scripting with Ruby What is a scripting language? What is Ruby?

I/O

• puts prints its argument followed by a newline

• print does not append a newline

• printf for formatted output

• gets reads a line– default destination is $_

Page 25: Scripting with Ruby What is a scripting language? What is Ruby?

Boolean expressions

• Anything that is not false or nil is true.– Note: 0 is not false

• The logical operators are– and, &&– or, ||– not, !– isDefined?

Page 26: Scripting with Ruby What is a scripting language? What is Ruby?

Relational Operators

== equal value=== case equality<=> like compareTo< <= >= >=~ matcheseql? Compares valuesequal? Compares object id

Page 27: Scripting with Ruby What is a scripting language? What is Ruby?

Selection• if statement

if <condition> <statements>

elsif <condition> <statements>

else <statements>

end

• if statement modifier<statement> if <condition>

• unless statement modifier<statement> unless <condition>

Page 28: Scripting with Ruby What is a scripting language? What is Ruby?

Case Expressions

• Multiway selectioncase yearwhen <range, boolean, pattern>

end

Page 29: Scripting with Ruby What is a scripting language? What is Ruby?

Repetition

• while statementwhile <condition>

<statements>

end

• while statement modifier<statement> while <condition>

• until statement modifier<statement> until <condition>

Page 30: Scripting with Ruby What is a scripting language? What is Ruby?

Conditional Modifiers

• There are four modifiers that can control whether a single statement gets executed– if– unless– while– until

• The syntax is<statement> <modifier> <condition>

Page 31: Scripting with Ruby What is a scripting language? What is Ruby?

Blocks

• Chunk of code that can be passed to a method– behaves like an anonymous (unnamed) function– often used with iterators

• Two formsdo <statements> end{|<paramlist>| <statements }

• A method can have a block as a parameter – block is executed by typing yield

Page 32: Scripting with Ruby What is a scripting language? What is Ruby?

Iterators

• Blocks are used to implement iterators• Pseudocode for typical iterator

def each for each element

yield element endend

Page 33: Scripting with Ruby What is a scripting language? What is Ruby?

Methods

• Return value of a method is the value of the last statement executed– irb prints value of each statement it executes

• Syntax for definingdef fnName

<statements>

end

Page 34: Scripting with Ruby What is a scripting language? What is Ruby?

Classes

• Attributes are private (@varname)– attr_reader to sepcify accessors

– attr_writer to specify mutators

• Class variables (@@varname)– methods called with class name

• private, protected, public access for methods

Page 35: Scripting with Ruby What is a scripting language? What is Ruby?

For more information

• David Thomas and Andrew Hunt, Programming Ruby, The Pragmatic Programmer's Guide, Addison Wesley

• David Flanagan and Yukihiro Matsumoto, The Ruby programming language in Safari Books online at library

Page 36: Scripting with Ruby What is a scripting language? What is Ruby?

On the Web

• Ruby home pagehttp://www.ruby-lang.org/en/

• 10 Things Every Java Programmer Should Know About Rubyhttp://onestepback.org/articles/10things/

index.html