Upload
phungtruc
View
215
Download
0
Embed Size (px)
Citation preview
Computer Science and Engineering ■ College of Engineering ■ The Ohio State University
Ruby: Introduction, Basics
Lecture 3
Computer Science and Engineering ■ The Ohio State University
Ruby vs Java: Similarities
□ Imperative and object-oriented ■ Classes and instances (ie objects) ■ Inheritance
□ Strongly typed ■ Classes determine valid operations
□ Some familiar operators ■ Arithmetic, bitwise, comparison, logical
□ Some familiar keywords ■ if, then, else, while, for, class, new…
Computer Science and Engineering ■ The Ohio State University
But Ruby Looks Different
□ Punctuation ■ Omit: ;'s and ()'s on function calls ■ Include: Function names ending in ? and !
□ New keywords and operators ■ def, do..end, yield, unless ■ ** (exp), =~ (match), <=> (spaceship)
□ Rich core libraries ■ Collections: Hashes, Arrays ■ Strings and regular expressions ■ Enumerators for iteration
Computer Science and Engineering ■ The Ohio State University
Deeper Differences As Well
□ Interpreted (typically) ■ Run a program directly, without compiling
□ Dynamically typed ■ Objects have types, variables don't
□ Everything is an object ■ C.f. primitives in Java
□ Code can be passed in to a function as a parameter ■ Added to Java in version 8 ("lambdas")
Computer Science and Engineering ■ The Ohio State University
Compiling Programs
□ Program = Text file ■ Contains easy-to-understand statements
like "print", "if", "while", etc. □ But a computer can only execute
machine instructions ■ Instruction set architecture of the CPU
□ A compiler translates the program (source code) into an executable (machine code) ■ Recall "Bugs World" from CSE 2231
□ Examples: C, C++, Objective-C, Ada…
Computer Science and Engineering ■ The Ohio State University
Interpreting Programs
□ An interpreter reads a program and executes it directly
□ Advantages ■ Platform independence ■ Read-eval-print loop (aka REPL) ■ Reflection
□ Disadvantages ■ Speed ■ Later error detection (i.e., at run time)
□ Examples: JavaScript, Python, Ruby
Computer Science and Engineering ■ The Ohio State University
Combination of Both
□ A language is not inherently compiled or interpreted ■ A property of its implementation
□ Sometimes a combination is used: ■ Compile source code into an intermediate
representation (byte code) ■ Interpret the byte code
□ Examples of combination: Java, C#
Computer Science and Engineering ■ The Ohio State University
Ruby is (Usually) Interpretted
□ REPL with Ruby interpreter, irb $ irb >> 3 + 4 => 7 >> puts "hello world" hello world => nil >> def square(x) x**2 end => :square >> square -4 => 16
Computer Science and Engineering ■ The Ohio State University
Literals
□ Numbers (FixNum, Float, Rational, Complex) 83, 0123, 0x53, 0b1010011, 0b101_0011 123.45, 1.2345e2, 12345E-2 2/3r, 4+3i
□ Strings ■Delimeters " " and ' ' ■Interpolation of #{…} occurs (only) inside " " "Sum 6+3 is #{6+3}" is "Sum 6+3 is 9" ■Custom delimeter with %Q�…� or %q�…�
□ Ranges ■0..4 includes start and end value (0,1,2,3,4) ■"cab"..."cat" does not include end value
□ Arrays and hashes (later)
Computer Science and Engineering ■ The Ohio State University
Comments and Statements
□ Single-line comments start with # ■ Don't confuse it with string interpolation!
□ Multi-line comments bracketed by =begin =end ■ Must appear at beginning of line
□ All statements have a value result □ Convention: => to indicate result
"Hi #{name}" + "!" #=> "Hi Liam!"
Computer Science and Engineering ■ The Ohio State University
Operators
□ Arithmetic: + - * / % ** ■ / is either ÷ or div, depending on operands ■ Integer / (div) rounds towards -∞, not 0 ■ % is modulus, not remainder 1 / 3.0 #=> 0.3333333333333333 1 / 3 #=> 0 (same as Java) -1 / 3 #=> -1 (not 0 as in Java) -1 % 3 #=> 2 (not -1 as in Java)
□ Bitwise: ~ | & ^ << >> 5 | 2 #=> 7 (ie 0b101 | 0b10) 13 ^ 6 #=> 11 (ie 0b1101 ^ 0b0110) 5 << 2 #=> 20 (ie 0b101 << 2)
Computer Science and Engineering ■ The Ohio State University
Operators (Continued)
□ Comparison: < > <= >= <=> ■ Last is so-called "spaceship operator" ■ Returns -1/0/1 iff LHS is smaller/equal/
larger than RHS "cab" <=> "da" #=> -1 "cab" <=> "ba" #=> 1
□ Logical: && || ! and or not ■ Words have low precedence (below =) ■ "do_this or die" idiom needs low-binding x = crazy or raise "problem"
Computer Science and Engineering ■ The Ohio State University
Pseudo Variables
□ Objects ■ self, the receiver of the current method
(recall this) ■ nil, nothingness (recall null)
□ Booleans ■ true, false ■ nil also evaluates to false ■ 0 is not false, it is true just like 1 or -4!
□ Specials ■ __FILE__, the current source file name ■ __LINE__, the current line number
Computer Science and Engineering ■ The Ohio State University
Significance in Names
□ A variable's name affects semantics! □ Variable name determines its scope ■ Local: start with lowercase letter (or _) ■ Global: start with $
□ Many pre-defined global variables exist, e.g.: ■ $/ is the input record separator (newline) ■ $; is the default field separator (space)
■ Instance: start with @ ■ Class: start with @@
□ Variable name determines mutability ■ Constant: start with uppercase, eg Size
but idiom is all upper case, eg SIZE
Computer Science and Engineering ■ The Ohio State University
Basic Statements: Conditionals
□ Classic structure if (boolean_condition) [then] ... else ... end
□ But usually omit ( )'s and "then" keyword if x < 10 puts "small" end
□ "If" keyword also a statement modifier x = x + 1 if x < LIMIT ■Good for single-line body ■Good when statement execution is common case ■Good for positive conditions
Computer Science and Engineering ■ The Ohio State University
Variations on Conditionals
□ Unless: equivalent to "if not…" unless size >= 10 puts "small" end ■Can also be a statement modifier x = x + 1 unless x >= LIMIT ■Same idiom: single-line body, execution is common case, and positive condition
□ Do not use "else" with "unless" □ Do not use negation in condition □ Do not use else with statement modifiers
Computer Science and Engineering ■ The Ohio State University
Pitfalls with Conditionals
□ Keyword "elsif" instead of "else if" if x < 10 puts "small" elsif x < 20 puts "medium" else puts "large" end
□ If's do not create nested lexical scope if x < 10 y = x end puts y #y is defined, but could be nil puts z #NameError: undefined local var z
Computer Science and Engineering ■ The Ohio State University
Case Statements are General[variable = ] case expression when nil statements execute if the expr was nil when value # e.g. 0, 'start' statements execute if expr equals value when type # e.g. String statements execute if expr resulted in Type when /regexp/ # e.g. /[aeiou]/ statements execute if expr matches regexp when min..max statements execute if the expr is in range else statements end
Computer Science and Engineering ■ The Ohio State University
Basic Iteration: While and Until
□ Classic structure while boolean_condition [do] … end ■Can also be used as a statement modifier work while awake
□ Until: equivalent to "while not…" until i > count … end ■Can also be a used as a statement modifier
□ Pitfall: Modified block executes at least once sleep while dark #may not sleep at all begin i = i + 1 end while i < MAX #always increments i at least once
Computer Science and Engineering ■ The Ohio State University
Functions□ Definition: keyword def
def foo (x, y) x + y end
□ Notice: no types in signature □ No types for parameters □ No types for return value
□ All functions return something □ Value of last statement implicitly returned □ Convention: Omit explicit return statement
def foo(x, y)
x + y # last statement executed
end
Computer Science and Engineering ■ The Ohio State University
Functions□ Dot notation for method call
Math::PI.rationalize() #rec’vr Math::PI
□ Convention: Omit ()’s in definition of functions with no parameters def launch() … end #bad def launch … end #good
□ Parens can be omitted in calls too! Math::PI.rationalize puts “Hello World” ■Convention: omit for “keyword-like” calls attr_reader :name, :age ■Note: needed when chaining foo(13).equal? value
Computer Science and Engineering ■ The Ohio State University
Summary
□ Ruby is a general-purpose, imperative, object-oriented language
□ Ruby is (usually) interpreted ■ REPL
□ Familiar flow-of-control and syntax ■ Some new constructs (e.g., unless, until) ■ Terse (e.g., optional parentheses, optional
semicolons, statement modifiers)
Computer Science and Engineering ■ The Ohio State University
Primitive vs Reference Types
□ Recall Java type dichotomy: ■ Primitive: int, float, double, boolean,… ■ Reference: String, Set, NaturalNumber,…
□ A variable is a "slot" in memory ■ Primitive: the slot holds the value itself ■ Reference: the slot holds a pointer to the
value (an object)
dwidth: 12 height: 15 color: "blue"
34
a
Computer Science and Engineering ■ The Ohio State University
Object Value vs Reference Value
□ Variable of reference type has both: ■ Reference value: value of the slot itself ■ Object value: value of object it points to
(corresponding to its mathematical value) □ Variable of primitive type has just one ■ Value of the slot itself, corresponding to its
mathematical value
dwidth: 12 height: 15 color: "blue"
34
a
Computer Science and Engineering ■ The Ohio State University
Two Kinds of Equality
□ Question: "Is x equal to y?" ■ A question about the mathematical value
of the variables x and y □ In Java, depending on the type of x
and y we either need to: ■ Compare the values of the slots x == y // for primitive types ■ Compare the values of the objects x.equals(y) // for non-primitive types
Computer Science and Engineering ■ The Ohio State University
Ruby: "Everything is an Object"
□ In Ruby, every variable maps to an object ■ Integers, floats, strings, sets, arrays, …
□ Benefit: A more consistent mental model ■ References are everywhere ■ Every variable has both a reference value and
an object value ■ Equality of mathematical value always means
comparing object values □ Ruby terminology: Reference value is
called the "object id" ■ The 4- or 8-byte number stored in the slot ■ Unique identifier for corresponding object msg = "hi" msg.object_id #=> 1544150170
Computer Science and Engineering ■ The Ohio State University
Everything is an Object
dwidth: 12 height: 15 color: "blue"a
34
msg
"shark"
true
<1,2,8,2>
list
done
Computer Science and Engineering ■ The Ohio State University
Operational Detail: Immediates
□ For small integers, the mathematical value is encoded in the reference value! ■ LSB of reference value is 1 ■ Remaining bits encode value, 2's complement x = 0 x.object_id #=> 1 (0b00000001) y = 6 y.object_id #=> 13 (0b00001101)
□ Benefit: Performance ■ No change to model (everything is an object)
□ Known as an "immediate" value ■ Other immediates: true, false, nil, symbols
Computer Science and Engineering ■ The Ohio State University
Objects Have Methods
□ Familiar "." operator to invoke (instance) methods list = [6, 15, 3, -2] list.size #=> 4
□ Since numbers are objects, they have methods too! 3.to_s #=> "3" 3.odd? #=> true 3.lcm 5 #=> 15 3.+ 5 #=> 8 3.class #=> FixNum 3.methods #=> [:to_s, :inspect, :+, …]
Computer Science and Engineering ■ The Ohio State University
Pitfall: Equality Operator
□ Reference value is still useful sometimes ■ "Do these variables refer to the same object?"
□ So we still need 2 methods: x == y x.equal? y
□ Ruby semantics are the opposite of Java! ■ == is object value equality ■ .equal? is reference value equality
□ Example s1, s2 = "hi", "hi" s1 == s2 #=> true (obj values equal) s1.equal? s2 #=> false (ref vals differ)
Computer Science and Engineering ■ The Ohio State University
Assignment (Just Like Java)
□ Assignment copies the reference value □ Result: Both variables point to the
same object (ie an "alias") □ Parameter passing works this way too
a b
<5, 1> <3, 4>
Computer Science and Engineering ■ The Ohio State University
Assignment (Just Like Java)
□ Assignment copies the reference value □ Result: Both variables point to the
same object (ie an "alias") □ Parameter passing works this way too
a b
a = b;
<5, 1> <3, 4>
a b
<5, 1> <3, 4>
Computer Science and Engineering ■ The Ohio State University
Assignment (Just Like Java)
□ Assignment copies the reference value □ Result: Both variables point to the
same object (ie an "alias") □ Parameter passing works this way too
a b
a = b;
<5, 1> <3, 4>
a b
<5, 1> <3, 4>
Computer Science and Engineering ■ The Ohio State University
Aliasing Mutable Objects
□ When aliases exist, a statement can change a variable's object value without mentioning that variable x = [3, 4] y = x # x and y are aliases y[0] = 13 # changes x as well!
□ Question: What about numbers? i = 34 j = i # i and j are aliases j = j + 1 # does this increment i too?
Computer Science and Engineering ■ The Ohio State University
Immutability
□ Recall in Java strings are immutable ■ No method changes the value of a string ■ A method like concat returns a new instance
□ Benefit: Aliasing immutable objects is safe □ Immutability is used in Ruby too
■ Numbers, true, false, nil, symbols list = [3, 4] list[0] = 13 # changes list's object value # list points to same object n = 34 n = n + 1 # changes n's reference value # n points to different object ■ Pitfall: Unlike Java, strings in Ruby are mutable
Computer Science and Engineering ■ The Ohio State University
Assignment Operators
□ Arithmetic contraction ■ += -= *= /= %= **= ■ Pitfall: no ++ or -- operators (use += 1)
□ Logical contraction ■ ||= &&= ■ Idiom: ||= for initializing potentially nil
variables ■ Pitfall (minor):
□ x ||= y not quite equivalent to x = x || y □ Better to think of it as x || x = y □ Usually amounts to the same thing
□ Parallel assignment x, y, z = y, 10, radius
Computer Science and Engineering ■ The Ohio State University
Declared vs Dynamic Types
□ In Java, types are associated with both ■ Variables ("declared" / "static" type), and ■ Objects ("dynamic" / "run-time" type) Queue line = new Queue1L();
□ Recall: Programming to the interface □ Compiler uses declared type for checks
line.inc(); //error no such method line = new Set1L(); //error wrong type
boolean isEmpty (Set s) {…} if isEmpty(line) … //error arg type
Computer Science and Engineering ■ The Ohio State University
Statically Typed Language
dwidth: 12 height: 15 color: "blue"
msg
"hello"
<1, 2, 8, 2>
line
Queue Queue1L
String String
ShapeRectangle
Computer Science and Engineering ■ The Ohio State University
Dynamically Typed Language
dwidth: 12 height: 15 color: "blue"
msg
"hello"
<1, 2, 8, 2>
line
Queue1L
String
Rectangle
Computer Science and Engineering ■ The Ohio State University
Dynamically Typed Language
□ Equivalent definitions: ■ No static types ■ Dynamic types only ■ Variables do not have type, objects do
Computer Science and Engineering ■ The Ohio State University
Function Signatures
□ Statically typed String parse(char[] s, int i) {… return e;} out = parse(t, x);
■ Parameter types (i.e. s and i) are declared ■ Return type (i.e. of parse) is declared ■ The compiler checks conformance of
□(Declared) types of arguments (t, x) □(Declared) type of return expression (e) □(Declared) type of expression using parse (out)
□ Dynamically typed def parse(s, i) … end out = parse t, x
■ You are on your own!
Computer Science and Engineering ■ The Ohio State University
Type Can Change at Run-time
Statically Typed //a is undeclared String a; //a is null string a = "hi; //compile-time err a = "hi"; a = 3; //compile-time err a.push(); //compile-time err
Dynamically Typed //a is undefined a = a //a is nil a = "hi //load-time error a = "hi" a = 3 //a is now a number a.crazy //run-time error
Computer Science and Engineering ■ The Ohio State University
Changing Dynamic Type
msg
"hello"
<1, 2, 8, 2>
line
Queue1L
String
Computer Science and Engineering ■ The Ohio State University
Changing Dynamic Type
msg
"hello"
<1, 2, 8, 2>
line
Queue1L
String
msg, line = line, msg
Computer Science and Engineering ■ The Ohio State University
Changing Dynamic Type
msg
"hello"
<1, 2, 8, 2>
line
Queue1L
String
msg
"hello"
<1, 2, 8, 2>
line
Queue1L
String
msg, line = line, msg