Ruby Intro

nostalgicisolatedΛογισμικό & κατασκευή λογ/κού

4 Νοε 2013 (πριν από 3 χρόνια και 8 μήνες)

64 εμφανίσεις

and other languages…


The Ruby Programming Language,
Flanagan & Matsumoto (creator of Ruby)


How to execute


Program structure


Variables


name, keywords, binding,
scope,
lifetime


Data types


type system


primitives, strings, arrays, hashes


pointers/references


type conversions and equality


Expressions


Operators, overloading,
booleans
,
short
-
circuiting, conditional
expression


Referential transparency


Statements
vs

Expressions


Control flow


conditionals


loops


Functions


Classes


Exception handling


Other features


Threads


Reflection


Libraries



Scanner (lexical analyzer): identifies the
tokens of a program statement


Parser (syntax analyzer): determines
whether the statement is valid, based on
the language definition/grammar



int

count = 20;


Tokens:

int

count

=

20

;

Grammar:

Based on BNF


Whitespace: mostly ignored


Statement separators: newline


use caution if statement doesn’t fit on one line


insert newline after operator, period or comma


OR escape the newline
*


No ( ) needed for function invocation


if use (), don’t put space after function name!


f(3+2)+1 != f (3+2)+1


# comments, or =begin/=end (start of
line)

Compare to Java/C++/Python

* think: how does interpreter recognize tokens/statement?


Basic unit is
expression


Primary expressions
: true, false, nil, self,
number and string literals, variable
references (all represent values)


Expressions: arithmetic,
boolean


Methods


Classes


Modules


Expression
vs

statement?

10.times { puts “hello” }


x = 5

unless x == 10


print x

end



Blocks can be nested. Indent for clarity.


block surrounded by { }

block delimited by “end”

often call this the “body”

never delimit with { }

Compare to Java/C++


length: no limit (
afaik
)


valid characters:


letters, numbers, _


can’t start with number


$ used as first character of global
var


@/@@ used to identify instance and class variables


? (convention) end method name with ? if returns
boolean


! (convention) end method name with ! if dangerous


= used to make assignments (covered with classes)


no other punctuation


support for Unicode


first letter (enforced by ruby):


Constants, classes and modules begin with A
-
Z


case sensitive




Compare to Java/C++/Fortran


many words have special meaning (e.g.
if, true, def, etc.)


Keyword
: has special meaning, but can
be used as variable name


Reserved
: can’t be used as variable


Ruby:
keyword
… can prefix with @, @@
or $ and use as variable name

Compare to Java/C++


A
binding

is an association, such as:


bind type of variable


bind operation to symbol (e.g., meaning of *)


bind function to its definition


Binding time

is the time at which a
binding takes place.


Type binding



may be static or dynamic


explicit or implicit



Language design time
--

bind operator symbols to operations :
sum = sum
+

count


Language implementation time
--

bind type to a representation :
int

=> number of bits, etc.


Compile time
--

bind a variable to a type:

int

count;


Link time


bind library subprogram to code:
cout

<< x;


Load time
--

bind a FORTRAN 77 variable to a memory cell (or a
C
static

variable)


Runtime

--

bind a
nonstatic

local variable to a memory cell



A binding is
static

if it first occurs
before run
time

and remains
unchanged

throughout
program execution.


A binding is
dynamic

if it first occurs
during
execution
or
can change during execution
of the
program




NOTE: doesn't consider paging etc. which is at
the hardware level



Type not specified by declaration, not
determined by name (JavaScript, PHP, Ruby)


Specified through an assignment statement



list = [2, 4.33, 6, 8];



list = 17.3;


Advantage: flexibility (
generic program units
)


Disadvantages:


High cost (dynamic type checking requires run
-
time
descriptors, normally interpreted)


Type error detection by the compiler is difficult


i

= x; // desired, x is scalar

i

= y; // typed accidentally, y is array


An
explicit declaration

is a program statement used for
declaring the types of variables:
int

count;


An
implicit declaration

is a default mechanism for
specifying types of variables (the first appearance of
the variable in the program)


Both create
static bindings
to types (i.e., type doesn’t
change during execution of program)


FORTRAN, PL/I, BASIC, and Perl provide implicit
declarations


Advantage:
writability


Disadvantage: reliability


Perl: @ is array, % is hash, $ is scalar


Fortran: I
-
N integer, others single precision, can
override




Numeric


Integer


allows base 8, 16, 2 (binary)


Fixnum
: fit in 31 bits


Bignum
: arbitrary size


Float


includes scientific notation


Complex


BigDecimal
: use decimal rather than binary rep


Rational

C++ has unsigned
ints
, Java does not…
concept doesn’t apply to Ruby


why?

COBOL was for business… inherent big
decimal. Java/C# provide. C++ does not.
Adv: accuracy.
Disadv
: waste space


-
7/3 =
-
3 in Ruby,
-
2 in Java/C++


div = integer division


fdiv

= floating point division


quo = rational division


Float::MAX


Infinity


Numbers are immutable (as you’d expect)




String literals


single quote


‘A ruby string’



Didn
\
’t you have fun?’


Only escape
\
’ or
\
\


newlines are embedded if multi
-
line


String literals


double quote


normal escape sequences (
\
t,
\
n etc)


string interpolation

w=5

h=4

puts "The area is #{w*h}"




Other languages with interpolation?


Strings are
mutable

in Ruby


+ is concatenation (often prefer interpolation)

age = 32

puts "I am " +
age.to_s


<< is append

s = "Hello"

s << " World"

puts s


Extract characters

puts s[0, 5]


* repeats text

puts "hey " * 5


Java converts right
-
hand to string, Ruby
doesn’t


Changed from Ruby 1.8 to Ruby 1.9


Characters are now strings of length 1



Not covered


multi
-
byte characters (need for
unicode
… 16
-
bit
encoding, first 128 the same as ASCII)


specify encodings (e.g., ASCII
-
8BIT, BINARY, US
-
ASCII, ASCII, ISO
-
8859
-
15, UTF
-
8)


many other String methods, such as
downcase
,
upcase
, chop, delete,
tr
, etc.

Does Java support
unicode
? Does C++?

Python also has strings of length 1, not primitive chars


Ruby is a
scripting

language


No special main method


In general, script starts executing with line
1, continues until all lines executed


Methods/classes come into existence when
they are read in the file


May use BEGIN/END (not common to do)


BEGIN { # global init code ]


END { #global shutdown code]


if multiple BEGINS, interpreter executes in order
read



open IRB


puts “say Hi”

say Hi


nil


nil is return… ruby has expressions, not
statements


Open text editor


puts “say Hi”


save file as demo1.rb


at command line: ruby demo1.rb



Can use [] with:



[ix]


[
ix,len
]


[ix..ix]


[
-
ix]


stringname.length
, etc.


if index too large, just returns nil


Try:


s = "Sunday, Monday, Tuesday, Wednesday, Thursday, Friday"


Find different ways to extract Sunday, Monday and Friday


Use different ways to modify the string (e.g., convert the string
to:


Monday, day, Tuesday, Wednesday, Thursday, Saturday)


Nothing to submit; no right answers


just play!


Compare to C/C++


Do Ruby Intro homework