Ruby: Objects and Dynamic Types

Similar documents
Ruby: Introduction, Basics

JavaScript: Introduction, Types

Ruby: Introduction, Basics

Ruby: Introduction, Basics

CS 11 java track: lecture 1

Pointers (continued), arrays and strings

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Zheng-Liang Lu Java Programming 45 / 79

Pointers (continued), arrays and strings

Introduction to Programming Using Java (98-388)

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

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

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

Chapter 1 Getting Started

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

VARIABLES AND TYPES CITS1001

CS2141 Software Development using C/C++ C++ Basics

Java and C CSE 351 Spring

Chapter 2: Data and Expressions

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

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

CS 231 Data Structures and Algorithms, Fall 2016

CSE 341, Autumn 2015, Ruby Introduction Summary

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Java Primer 1: Types, Classes and Operators

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Chapter 2: Using Data

Programming refresher and intro to C programming

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

CISC 1600 Lecture 3.1 Introduction to Processing

A brief introduction to C programming for Java programmers

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Motivation was to facilitate development of systems software, especially OS development.

Organization of Programming Languages CS320/520N. Lecture 06. Razvan C. Bunescu School of Electrical Engineering and Computer Science

CMSC 132: Object-Oriented Programming II

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

Introduction to Programming (Java) 2/12

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

CS61C : Machine Structures

Motivation was to facilitate development of systems software, especially OS development.

Assumptions. History

Object typing and subtypes

Where We Are. Lexical Analysis. Syntax Analysis. IR Generation. IR Optimization. Code Generation. Machine Code. Optimization.

CMSC 430 Introduction to Compilers. Fall Everything (else) you always wanted to know about OCaml (but were afraid to ask)

MODULE 02: BASIC COMPUTATION IN JAVA

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

6.001 Notes: Section 6.1

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

CMSC330. Objects, Functional Programming, and lambda calculus

Chapter 2: Data and Expressions

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking

All classes in a package can be imported by using only one import statement. If the postcondition of a method is not met, blame its implementer

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

CS 61c: Great Ideas in Computer Architecture

COP 3330 Final Exam Review

Java and C I. CSE 351 Spring Instructor: Ruth Anderson

Chapter 2: Data and Expressions

Arithmetic and Bitwise Operations on Binary Data

Pierce Ch. 3, 8, 11, 15. Type Systems

CS558 Programming Languages

ITI Introduction to Computing II

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

CSE450. Translation of Programming Languages. Lecture 11: Semantic Analysis: Types & Type Checking

Organization of Programming Languages CS3200 / 5200N. Lecture 06

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Announcements. My office hours are today in Gates 160 from 1PM-3PM. Programming Project 3 checkpoint due tomorrow night at 11:59PM.

Data III & Integers I

Programming Languages and Techniques (CIS120)

Chapter 6 Classes and Objects

JAVA MOCK TEST JAVA MOCK TEST II

Computer Science is...

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Full file at

1 Shyam sir JAVA Notes

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP-202: Foundations of Programming. Lecture 16: Reference types Jackie Cheung, Winter 2016

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Programming Languages and Techniques (CIS120)

CMPT 125: Lecture 3 Data and Expressions

Programming Lecture 3

CS558 Programming Languages

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Topic 7: Algebraic Data Types

CS 251 Intermediate Programming Methods and Classes

1007 Imperative Programming Part II

CS 251 Intermediate Programming Methods and More

Full file at

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Type Checking and Type Equality

Building Java Programs

Visual C# Instructor s Manual Table of Contents

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413

Transcription:

Ruby: Objects and Dynamic Types Computer Science and Engineering College of Engineering The Ohio State University Lecture 5

Primitive vs Reference Types Recall Java type dichotomy: Primitive: int, float, double, boolean, Reference:, 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) a 34 d width: 12 height: 15 color: "blue"

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 a 34 d width: 12 height: 15 color: "blue"

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

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

Everything is an Object a 34 d width: 12 height: 15 color: "blue" done msg true "shark" list <1,2,8,2>

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 y = 6 y.object_id #=> 1 (0b00000001) #=> 13 (0b00001101) Benefit: Performance No change to model (everything is an object) Known as an "immediate" value Other immediates: true, false, nil, symbols

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, :+, ]

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)

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>

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 a = b; <5, 1> <3, 4> <5, 1> <3, 4>

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 a = b; <5, 1> <3, 4> <5, 1> <3, 4>

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?

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

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

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

Statically Typed Language line Queue <1, 2, 8, 2> Queue1L msg d Shape "hello" width: 12 height: 15 color: "blue" Rectangle

Dynamically Typed Language line <1, 2, 8, 2> Queue1L msg "hello" d width: 12 height: 15 color: "blue" Rectangle

Dynamically Typed Language Equivalent definitions: No static types Dynamic types only Variables do not have type, objects do

Function Signatures Statically typed parse(char[] s, int i) { return e;} out = parse(t, x); Declare parameter and return types See s, i, and parse 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) e end out = parse t, x You are on your own!

Type Can Change at Run-time Statically Typed //a is undeclared 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

Changing Dynamic Type line <1, 2, 8, 2> Queue1L msg "hello"

Changing Dynamic Type msg, line = line, msg line <1, 2, 8, 2> Queue1L msg "hello"

Changing Dynamic Type msg, line = line, msg line line <1, 2, 8, 2> Queue1L <1, 2, 8, 2> Queue1L msg msg "hello" "hello"

Arrays: Static Typing msg "hello" msg = "hello";

Arrays: Static Typing msg msgs "hello" msg = "hello"; [] msgs = ["hello", "world", "hi there"]; [] "hello" "world" "hi there"

Arrays: Dynamic Typing msg msgs "hello" msg = "hello"; msgs = ["hello", "world", "hi there"]; "hello" "world" "hi there"

Consequence: Heterogeneity msgs msgs = ["hello", 3.14, 17]; "hello" 3.14 Float 17 FixNum

Tradeoffs Statically Typed Earlier error detection Clearer APIs More compiler optimizations Richer IDE support Dynamically Typed Less code to write Less code to change Quicker prototyping No casting needed

Strongly Typed Just because variables don't have types, doesn't mean you can do anything you want >> "hi".upcase => "HI" >> "hi".odd? NoMethodError: undefined method `odd?' for >> puts "The value of x is " + x TypeError: can't convert Fixnum to

Summary Object-oriented References are everywhere Assignment copies reference value (alias) Primitives (immediates) are objects too == vs.equal? are flipped Dynamically type Objects have types, variables do not Strongly Typed Incompatible types produce (run time) error