Programming Ruby, The Pragmatic Programmer's Guide

bricklayerbelchedInternet και Εφαρμογές Web

5 Φεβ 2013 (πριν από 4 χρόνια και 6 μήνες)

104 εμφανίσεις

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

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

Basic Scripting Languages


Unix and Linux come with shell programs
which are programmable


sh


bash


ksh


csh


DOS had BAT files

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


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


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

Scripting on onyx


the shell languages


sed


awk


perl


python


ruby


tcl



javascript


php

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


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 it

chmod +x prog.rb

./prog.rb


Use the
irb

command to get an interactive
session


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 #

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
$

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


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


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


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

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

String methods


split
,

scan
followed by optional regular
expression tokenize string


capitalize
,
capitalize!
,
downcase
,
downcase!


include?


index


length

Regular Expressions


Patterns enclosed between slashes

/<pattern>/


Operator =~ means matches (returns
boolean)


Uses perl syntax

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

Hashes


Creating


Use a literal

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


Use new

h2 = Hash.new

can specify value of missing element as argument to
new


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, dup, …

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
$_

Selection


if statement

if <condition> <statements>

elsif <condition> <statements>

else <statements>

end


if statement modifier

<statement> if <condition>


unless statement modifier

<statement> unless <condition>

Repetition


while statement

while <condition>


<statements>

end


while statement modifier

<statement> while <condition>


until statement modifier

<statement> until <condition>

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>

Blocks


Chunk of code that can be passed to a method


behaves like an anonymous (unnamed) function


often used with iterators


Two forms

do <statements> end

{|<paramlist>| <statements }


A method can have a block as a parameter


block is executed by typing
yield



Iterators


Blocks are used to implement iterators


Pseudocode for typical iterator

def each


for each element




yield element


end

end


Methods


Return value of a method is the value of the
last statement executed


irb

prints value of each statement it executes


Syntax for defining

def fnName

<statements>

end

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


For more information


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


Ruby home page

http://www.ruby
-
lang.org/en/