Programming Paradigms

Size: px
Start display at page:

Download "Programming Paradigms"

Transcription

1 PP 2016/17 Unit 4 Ruby Advanced 1/42 Programming Paradigms Unit 4 Ruby Advanced J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

2 PP 2016/17 Unit 4 Ruby Advanced 2/42 Outline 1 Functions, Code Blocks and Procs 2 Classes 3 Modules and Mixins

3 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 3/42 Outline 1 Functions, Code Blocks and Procs 2 Classes 3 Modules and Mixins

4 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 4/42 Defining Functions Functions are used to bundle one or more statements into a single unit They can be defined in the console, and without defining a class first Functions are also referred to as methods >> def tell the truth >> true => nil >> tell the truth => true Every function returns something: if no explicit return expr1, expr2,... statement is used, the value of the last processed expression is returned More than one values are returned in an array Like everything else, functions in Ruby are considered objects You can call tell the truth.class or tell the truth.methods

5 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 5/42 Positional Parameters to Functions Functions accept parameters The default are positional parameters, i.e., the order of the parameters matters >> def method name (var1, var2) >> expr.. You can set default values for the parameters, which will be used if method is called without passing parameters >> def method name (var1=value1, var2=value2) >> expr... Function call >> method name param1, param2

6 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 6/42 Positional Parameters to Functions: Example Function with two parameters that are initialized >> def test(a1= Ruby, a2= Perl ) >> puts "The programming language is #{a1}" >> puts "The programming language is #{a2}" Call function with two parameters >> test C, C++ >> The programming language is C >> The programming language is C++ => nil Call function with one parameter (which is the first one) >> test C >> The programming language is C >> The programming language is Perl => nil

7 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 7/42 Named Parameters to Functions Before Ruby 2.0, there was no support for named parameters, which are specified/referred to by a name in the function call For example, in Objective-C a function call can look like this: [window addnew:@"title" xposition:20 yposition:50 width:100 height:50 drawingnow:yes]; Named parameters simplify, e.g., the handling of optional parameters the parameters can be passed in any order

8 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 8/42 Named Parameters Using Hashes A single hash can be used to emulate named parameters (only way before Ruby 2.0) >> def tell the truth(options = {}) >> case options[:profession] >> when :lawyer >> almost certainly not false >> when :doctor >> true >> else >> yep >> tell the truth( :profession => :lawyer ) => "almost certainly not false" >> tell the truth => "yep"

9 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 9/42 Named Parameters as Keyword Arguments Ruby 2.0 introduced keyword arguments, which are named parameters They are followed by a colon (:) and an optional default value When calling a method, the order of the arguments can be in any order without affecting the behavior (not the case for positional arguments) Parameters that are not initialized have to be specified >> def total(subtotal:, tax:10, discount:5) >> subtotal + tax - discount >> total(subtotal:100) => 105 >> total(subtotal:100, discount:20) => 190 >> total(subtotal:100, discount:20) => 190 >> total() ArgumentError: missing keyword: subtotal

10 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 10/42 Code Blocks/1 A code block is basically a function without a name It can be passed as a parameter to a function or method It is delimited by curly braces {...} (inline or single-line block) or do...end (multi-line block) >> 3.times { puts hello } hello hello hello => 3 times is an iterator (method) for the class Fixnum that does something a certain number of times

11 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 11/42 Code Blocks/2 Let s write our own version of times called log2times x.log2times does something log 2 (x) times class Fixnum def log2times i = self while i > 1 i = i / 2 yield end end end >> 2.log2times { puts Hello world! } Hello world! => nil >> 5.log2times { puts Hello world! } Hello world! Hello world! => nil self gives you access to the current object the object that is receiving the current message yield in the method log2times calls the passed code block Ruby has open classes: write an existing class definition, specify/define something and it will be added to the class The code extends the class Fixnum by adding a method log2times

12 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 12/42 Parameters to Code Blocks It is also possible to pass parameters to the code block In the block, a variable is placed in vertical lines to accept parameters >> (0..3).each { x puts x } => 0..3 x assumes the values What is the result of the following expression? Equivalent expression: (0..3).each do x puts x end >> [ 2, plus, 3, is, "#{2+3}"].each { x puts x }

13 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 13/42 Procs/1 Code blocks are not first-class citizens of Ruby For example, you cannot assign them to a variable >> y = { x puts x } syntax error,... If you want to do something other than yielding them, you have to convert them to a Proc, which is a class in Ruby, and you can create objects of this type >> y = Proc.new { x puts x } => #<Proc:0xb7367ac4> >> y.call(3) 3 => nil >> y.class => Proc

14 Functions, Code Blocks and Procs PP 2016/17 Unit 4 Ruby Advanced 14/42 Procs/2 Any code block can be turned into a Proc object if it is passed as a parameter and the parameter is preceded by an ampersand The code block (object) is then executed with the call method (similar to yield) This allows to pass around executible code >> def call block(&block) >> block.call => nil >> def pass block(&block) >> call block(&block) => nil >> pass block { puts Hello block! } Hello block! => nil

15 Classes PP 2016/17 Unit 4 Ruby Advanced 15/42 Outline 1 Functions, Code Blocks and Procs 2 Classes 3 Modules and Mixins

16 Classes PP 2016/17 Unit 4 Ruby Advanced 16/42 Class Hierarchy Ruby supports single inheritance, creating a hierarchy of classes The methods class and superclass can be used to obtain, respectively, the class of an object and the parent of a class >> 4.class => Fixnum >> Fixnum.superclass => Integer >> Integer.superclass => Numeric >> Numeric.superclass => Object >> Object.superclass => nil

17 Classes PP 2016/17 Unit 4 Ruby Advanced 17/42 Ruby Metamodel As in Ruby everything is an object, classes are themselves instances of the class Class >> 4.class.class => Class >> 4.class.superclass => Integer >> Numeric.superclass => Object >> 4.class.superclass.superclass.class => Class

18 Classes PP 2016/17 Unit 4 Ruby Advanced 18/42 Defining a Class/1 A class is made up of a collection of variables representing the internal state and methods providing behaviours that operate on that state Class names must begin with a capital letter By convention, names that contain more than one word are run together with each word capitalized, e.g., CamelCase Let s start building a class Customer >> class Customer => nil This is the simplest possible class: an empty class (doing nothing)

19 Classes PP 2016/17 Unit 4 Ruby Advanced 19/42 Defining a Class/2 Initializing the class and creating variables >> class Customer of customers=0 >> def initialize(name, addr) of customers of customers + 1 Class variables are prepended Belong to the class and have one value per class Instance variables are prepended Belong to the instances/objects and have different values for each instance Need not to be declared, but are dynamically appended to an object when they are first assigned The initialize method is executed when a new object is created

20 Classes PP 2016/17 Unit 4 Ruby Advanced 20/42 Accessor Methods for a Class/1 By default, variables are private and can only be directly accessed within an instance method To provide access from outside, accessor methods are needed Accessor methods can have the same name as variables... and addr= is a valid method name When you use them, it looks like you are accessing directly the variables >> class Customer >> def set name( name ) = name >> def get name >> >> def addr=( addr ) = addr >> def addr >> >> def get no of customers >> of customers

21 Classes PP 2016/17 Unit 4 Ruby Advanced 21/42 Accessor Methods for a Class/2 Now we can use our class >> c1 = Customer.new( max, meran ) >> c2 = Customer.new( moritz, meran ) >> c1.addr => "meran" >> c1.addr= bozen => "bozen" >> c1.addr => "bozen" >> c1.get no of customers => 2

22 Classes PP 2016/17 Unit 4 Ruby Advanced 22/42 Accessor Methods for a Class/3 Since getters and setters are so common, they can be autogenerated >> class Customer of customers=0 >> attr accessor :name, :addr attr accessor is a method, which is run when Ruby constructs the class object, and it generates the setter and getter methods for you addr=(addr), addr, name=(name), and name If instead attr :name, :addr is used, only the getter methods are created

23 Classes PP 2016/17 Unit 4 Ruby Advanced 23/42 Example Tree Class Let s build a class Tree, which allows to create a tree and to traverse it class Tree attr accessor :children, :node name def initialize(name, name = = children end def traverse(&block) process &block children.each { c c.traverse &block} end def process(&block) block.call self end end

24 Classes PP 2016/17 Unit 4 Ruby Advanced 24/42 Using the Tree Class Let s create a tree with root node Ruby and children Reia and MacRuby rubytree = Tree.new( Ruby, [Tree.new( Reia ),Tree.new( MacRuby )]) Processing the root node by outputting its name rubytree.process { node puts node.node name} Ruby Traversing the whole tree (printing each node name) rubytree.traverse { node puts node.node name} Ruby Reia MacRuby

25 Classes PP 2016/17 Unit 4 Ruby Advanced 25/42 Inheritance If we want to create a red-black tree based on our Tree class, we need to add a color and a method for balancing the tree class RedBlackTree < Tree attr accessor :color def initialize(name, color, children=[]) super(name, = color end def balance()... end end < creates a subclass of an existing class super calls the initialize method of the superclass Tree In Ruby, a class can only inherit from a single other class

26 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 26/42 Outline 1 Functions, Code Blocks and Procs 2 Classes 3 Modules and Mixins

27 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 27/42 Modules/1 A module is a collection of (related) classes, methods/functions and constants module Identifier statement1 statement2... end A module comes together with its own namespace (to avoid name clashes) Similar to classes, but there are no instances (objects) of modules there is no inheritance

28 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 28/42 Modules/2 An example is the Math module >> module Math >> PI = >> def sqrt( v ) >> #... >> #... It defines various constants, e.g., PI, and functions, e.g., sqrt Constants begin with an uppercase letter

29 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 29/42 Using Modules To use modules, you can use either qualified names >> Math.sqrt(2) => >> Math::PI => or include the module >> include Math => Object >> sqrt(2) => >> PI =>

30 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 30/42 Modules and Classes Modules become really interesting when used in combination with classes Ruby does not support multiple inheritance However, it does support a mechanism called a mixin If we include a module in a class definition, the module s methods are appended to the class Effectively, the module is mixed in with the class

31 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 31/42 Mixins/1 Unfortunately, it is not that easy to create a mixin In order to use the full power of a module in a class, your class may need to implement certain methods Let s try to get the tree node names sorted in alphabetical order We ll try to do this mixing the module Enumerable into our class Enumerable provides a method called sort

32 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 32/42 Mixins/2 Just including the module Enumerable in our Tree class won t give us the full functionality: >> class Tree >> include Enumerable >> attr accessor :children, :node name >>... => nil >> ruby tree = Tree.new(...) =>... >> ruby tree.sort NoMethodError: undefined method each for... A class wanting to be enumerable must implement the method each to go through all elements In our Tree class, the method needs to go through all nodes

33 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 33/42 Mixins/3 Let s add the method each, which needs an object and a code block as parameter >> class Tree >> include Enumerable >> attr accessor :children, :node name >>... >> def each(&block) >> block.call self >> children.each { c c.each &block} >> ruby tree.sort NoMethodError: undefined method <=> for... We are missing yet another operator

34 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 34/42 Mixins/4 A class wanting to be comparable must implement the spaceship operator <=> This operator is used for comparing two objects: 1 if a < b a <=> b = 1 if a > b 0 if a = b Let s add this operator to our Tree class

35 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 35/42 Mixins/5 class Tree... def <=>(t) return -1 if self.node name < t.node name return 1 if self.node name > t.node name return 0 if self.node name == t.node name return nil end end >> ruby tree.sort => name="mcruby",... The output doesn t look very nice, sort returns an array of trees

36 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 36/42 Success! However, an array supports the method each as well So we can pass a code block to the array, printing the names of the nodes: >> (ruby tree.sort).each { n puts n.node name} McRuby Reia Ruby This small example already hints at the flexibility provided by modules, mixins, and code blocks

37 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 37/42 Success? Well, looking at the code for our Tree class you ll notice that some of the code is redundant Now that we ve implemented the each method, we don t need the traverse method anymore (which does essentially the same thing) So we can refactor the code to make it slimmer and better

38 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 38/42 Final Tree Class class Tree include Enumerable attr accessor :children, :node name def initialize(name, = name = name end def each(&block) block.call self children.each { c c.each &block} end def <=>(tree)... end end

39 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 39/42 Example Insertion Sort/1 Insertion sort iterates through a list of data, consuming one input element each repetition, and growing a sorted output list In each iteration, it removes one element from the input data, finds the correct position in the sorted output list, and inserts it there Sorting is typically done in-place, by iterating through the input array from the beginning, and growing the sorted list behind it In the array after k iterations the first k +1 entries are sorted If the current element is x it becomes after this iteration

40 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 40/42 Example Insertion Sort/2 Insertion sort in Java class InsertionSort{ static void sort(int[] a){ for (int i = 1; i < a.length; i++){ int val = a[i]; int j = i-1; } } while (j >= 0 && a[j] > val){ a[j+1] = a[j]; j--; } a[j+1] = val; } public static void main(string[] args){ int[] a = {2,43,24,100,3}; sort(a); for (int e : a) System.out.println(e); }

41 Modules and Mixins PP 2016/17 Unit 4 Ruby Advanced 41/42 Example Insertion Sort/3 Insertion sort in Ruby def insertionsort( a ) a.each index do i val = a[i] j = i - 1 while j >= 0 and a[j] > val a[j+1], a[j] = a[j], a[j+1] j -= 1 end end end a = [2,43,24,100,3] insertionsort(a) puts a

42 PP 2016/17 Unit 4 Ruby Advanced 42/42 Summary Strengths of Ruby Ruby is a pure object-oriented language, treating objects in a consistent way Ruby is a strongly typed language, but applies dynamic type checking Supports Duck typing, and is therefore very flexible when it comes to substitutability Some nice features not present in other languages: rich methods on arrays, code blocks, modules and mixins Programmers can be very productive using Ruby, can be used like a scripting language Comes with a very successful web development framework: Ruby on Rails The original Twitter implementation was done in Ruby Weaknesses of Ruby Performance: Ruby is not the most efficient language All the flexibility makes it difficult to compile programs Concurrent programming is difficult to do with a state-based language Type Safety: duck typing makes it harder to debug code that has type errors in it

Overview of the Ruby Language. By Ron Haley

Overview of the Ruby Language. By Ron Haley Overview of the Ruby Language By Ron Haley Outline Ruby About Ruby Installation Basics Ruby Conventions Arrays and Hashes Symbols Control Structures Regular Expressions Class vs. Module Blocks, Procs,

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 18 Summary of Basic Concepts 1/13 Programming Paradigms Unit 18 Summary of Basic Concepts J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE PP 2017/18 Unit 18

More information

CSE 341, Autumn 2015, Ruby Introduction Summary

CSE 341, Autumn 2015, Ruby Introduction Summary CSE 341, Autumn 2015, Ruby Introduction Summary Disclaimer: This lecture summary is not necessarily a complete substitute for atting class, reading the associated code, etc. It is designed to be a useful

More information

CS 5142 Scripting Languages

CS 5142 Scripting Languages CS 5142 Scripting Languages 10/25/2012 Ruby 1 Outline Ruby Martin Hirzel 2 About Ruby Invented 1995 by Yokihiro Matz Matsumoto Influenced by SmallTalk Everything is an object (even e.g., integers) Blocks

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

15.1 Origins and Uses of Ruby

15.1 Origins and Uses of Ruby 15.1 Origins and Uses of Ruby - Designed by Yukihiro Matsumoto; released in 1996 - Use spread rapidly in Japan - Use is now growing in part because of its use in Rails - A pure object-oriented purely interpreted

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Simple Java Reference

Simple Java Reference Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...

More information

Preview from Notesale.co.uk Page 3 of 36

Preview from Notesale.co.uk Page 3 of 36 all people who know the language. Similarly, programming languages also have a vocabulary, which is referred to as the set of keywords of that language, and a grammar, which is referred to as the syntax.

More information

Ruby: Object-Oriented Concepts

Ruby: Object-Oriented Concepts Ruby: Object-Oriented Concepts Computer Science and Engineering College of Engineering The Ohio State University Lecture 8 Classes Classes have methods and variables class LightBulb # name with CamelCase

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Programming Paradigms

Programming Paradigms PP 2016/17 Unit 5 Recursion 1/32 Programming Paradigms Unit 5 Recursion J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE PP 2016/17 Unit 5 Recursion 2/32 Outline 1 Recursion

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 12 Functions and Data Types in Haskell 1/45 Programming Paradigms Unit 12 Functions and Data Types in Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

More information

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed. Enums Introduction In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed. The Final Tag To display why this is useful, I m going to

More information

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 1. Introduction 2. Objects and classes 3. Information hiding 4. Constructors 5. Some examples of Java classes 6. Inheritance revisited 7. The class hierarchy

More information

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within

More information

SOAPScript For squeaky-clean code, use SOAPScript Language Summary Bob Nisco Version 0.5 β

SOAPScript For squeaky-clean code, use SOAPScript Language Summary Bob Nisco Version 0.5 β SOAPScript For squeaky-clean code, use SOAPScript Language Summary Bob Nisco Version 0.5 β This page intentionally left blank? It s a paradox more so than a question. Nisco 2 Nisco 3 1. Introduction SOAPScript,

More information

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018 Contents 1 Mutation in the Doghouse 1 1.1 Aside: Access Modifiers..................................

More information

Smalltalk: developed at Xerox Palo Alto Research Center by the Learning Research Group in the 1970 s (Smalltalk-72, Smalltalk-76, Smalltalk-80)

Smalltalk: developed at Xerox Palo Alto Research Center by the Learning Research Group in the 1970 s (Smalltalk-72, Smalltalk-76, Smalltalk-80) A Bit of History Some notable examples of early object-oriented languages and systems: Sketchpad (Ivan Sutherland s 1963 PhD dissertation) was the first system to use classes and instances (although Sketchpad

More information

Lecture 2. Object Orientation 1 / 51

Lecture 2. Object Orientation 1 / 51 Lecture 2 Object Orientation 1 / 51 Homework 1 Homework 1 was due at noon You will be graded on: Correctness: 15 points (passing all RSpec tests) Style: 5 points (having no Rubocop style offenses) Best

More information

Project 6 Due 11:59:59pm Thu, Dec 10, 2015

Project 6 Due 11:59:59pm Thu, Dec 10, 2015 Project 6 Due 11:59:59pm Thu, Dec 10, 2015 Updates None yet. Introduction In this project, you will add a static type checking system to the Rube programming language. Recall the formal syntax for Rube

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 11 Functional Programming with Haskell 1/37 Programming Paradigms Unit 11 Functional Programming with Haskell J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE

More information

Lecture 2. Object Orientation

Lecture 2. Object Orientation Lecture 2 Object Orientation 1 Homework 0 Grades Homework 0 grades were returned earlier this week Any questions? 2 Homework 1 Homework 1 is due tonight at 11:59pm You will be graded on: Correctness: 15

More information

Strings and Variables

Strings and Variables Strings and Variables class Player attr_accessor :name attr_reader :health def initialize(name, health=100) @name = name.capitalize @health = health @found_treasures = Hash.new(0) Inside the initialize

More information

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) David Haraburda January 30, 2013 1 Introduction Scala is a multi-paradigm language that runs on the JVM (is totally

More information

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative

More information

Classes and Objects in Ruby

Classes and Objects in Ruby Computer Science and Engineering IIT Bombay kuhoo@cse.iitb.ac.in Nov 29, 2004 Classes and Objects Rubby Object A set of flags, instance variables and an associated class Rubby Class An object of class

More information

Type Checking and Type Equality

Type Checking and Type Equality Type Checking and Type Equality Type systems are the biggest point of variation across programming languages. Even languages that look similar are often greatly different when it comes to their type systems.

More information

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1

A First Look At Java. Didactic Module 13 Programming Languages - EEL670 1 A First Look At Java Didactic Module 13 Programming Languages - EEL670 1 Outline Thinking about objects Simple expressions and statements Class definitions About references and pointers Getting started

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

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

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP Dan Grossman Winter 2013 Ruby logistics Next two sections use the Ruby language http://www.ruby-lang.org/ Installation / basic usage

More information

Multiple Inheritance using modules in Ruby

Multiple Inheritance using modules in Ruby Computer Science and Engineering IIT Bombay {amruta}@cse.iitb.ac.in November 29, 2004 Introduction Ruby is an interpreted scripting language for quick and easy object-oriented programming Important Features

More information

Objective-C. Stanford CS193p Fall 2013

Objective-C. Stanford CS193p Fall 2013 New language to learn! Strict superset of C Adds syntax for classes, methods, etc. A few things to think differently about (e.g. properties, dynamic binding) Most important concept to understand today:

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

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

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java OCaml Data : Organization of Programming Languages OCaml 4 Data Types & Modules So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists Ø One kind of data structure

More information

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

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework Ruby logistics CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP Dan Grossman Autumn 2018 Next two sections use the Ruby language http://www.ruby-lang.org/ Installation / basic usage

More information

In fact, as your program grows, you might imagine it organized by class and superclass, creating a kind of giant tree structure. At the base is the

In fact, as your program grows, you might imagine it organized by class and superclass, creating a kind of giant tree structure. At the base is the 6 Method Lookup and Constant Lookup As we saw in Chapter 5, classes play an important role in Ruby, holding method definitions and constant values, among other things. We also learned how Ruby implements

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

Computer Science II Lecture 1 Introduction and Background

Computer Science II Lecture 1 Introduction and Background Computer Science II Lecture 1 Introduction and Background Discussion of Syllabus Instructor, TAs, office hours Course web site, http://www.cs.rpi.edu/courses/fall04/cs2, will be up soon Course emphasis,

More information

Introduction to Ruby. Part I

Introduction to Ruby. Part I Introduction to Ruby Sebastian Fischer Part I Data Numbers, Strings, Ranges, Arrays/Hashes Control Branching, Loops, Iterators Numbers >> 42 => 42 >> -17 => -17 >> 1.23 => 1.23 >> 4.56e7 => 45600000.0

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

More information

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations

More information

Object Oriented Programming in C#

Object Oriented Programming in C# Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Fall 2017 CISC124 9/16/2017

Fall 2017 CISC124 9/16/2017 CISC124 Labs start this week in JEFF 155: Meet your TA. Check out the course web site, if you have not already done so. Watch lecture videos if you need to review anything we have already done. Problems

More information

Lecture 2. Object Orientation 1 / 50

Lecture 2. Object Orientation 1 / 50 Lecture 2 Object Orientation 1 / 50 Homework 1 Homework 1 was due last night You will be graded on: Correctness: 15 points (passing all RSpec tests) Style: 5 points (having no Rubocop style offenses) Best

More information

Ruby on Rails for PHP and Java Developers

Ruby on Rails for PHP and Java Developers Ruby on Rails for PHP and Java Developers Bearbeitet von Deepak Vohra 1. Auflage 2007. Taschenbuch. xvi, 394 S. Paperback ISBN 978 3 540 73144 3 Format (B x L): 15,5 x 23,5 cm Gewicht: 629 g Weitere Fachgebiete

More information

What is Ruby? CSc 372. Comparative Programming Languages. 27 : Ruby Introduction. Department of Computer Science University of Arizona

What is Ruby? CSc 372. Comparative Programming Languages. 27 : Ruby Introduction. Department of Computer Science University of Arizona What is Ruby? CSc 372 Comparative Programming Languages 27 : Ruby Introduction Department of Computer Science University of Arizona Everything is an object. Everything can be changed: method can be added

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Unit E Step-by-Step: Programming with Python

Unit E Step-by-Step: Programming with Python Unit E Step-by-Step: Programming with Python Computer Concepts 2016 ENHANCED EDITION 1 Unit Contents Section A: Hello World! Python Style Section B: The Wacky Word Game Section C: Build Your Own Calculator

More information

CEU s (Continuing Education Units) 12 Hours (i.e. Mon Thurs 5 9PM or Sat Sun 8AM 5PM)

CEU s (Continuing Education Units) 12 Hours (i.e. Mon Thurs 5 9PM or Sat Sun 8AM 5PM) Course Name: Intro to Ruby Course Number: WITP 312 Credits: Classroom Hours: 1.2 CEU s (Continuing Education Units) 12 Hours (i.e. Mon Thurs 5 9PM or Sat Sun 8AM 5PM) Flex Training - Classroom and On-Line

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

Java Review. Fundamentals of Computer Science

Java Review. Fundamentals of Computer Science Java Review Fundamentals of Computer Science Link to Head First pdf File https://zimslifeintcs.files.wordpress.com/2011/12/h ead-first-java-2nd-edition.pdf Outline Data Types Arrays Boolean Expressions

More information

Your First Ruby Script

Your First Ruby Script Learn Ruby in 50 pages Your First Ruby Script Step-By-Step Martin Miliauskas @mmiliauskas 1 Your First Ruby Script, Step-By-Step By Martin Miliauskas Published in 2013 by Martin Miliauskas On the web:

More information

Inheritance and Polymorphism in Java

Inheritance and Polymorphism in Java Inheritance and Polymorphism in Java Introduction In this article from my free Java 8 course, I will be discussing inheritance in Java. Similar to interfaces, inheritance allows a programmer to handle

More information

CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341

CSE 413 Spring Introduction to Ruby. Credit: Dan Grossman, CSE341 CSE 413 Spring 2011 Introduction to Ruby Credit: Dan Grossman, CSE341 Why? Because: Pure object-oriented language Interesting, not entirely obvious implications Interesting design decisions Type system,

More information

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

The software crisis. code reuse: The practice of writing program code once and using it in many contexts. Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

CIS133J. Working with Numbers in Java

CIS133J. Working with Numbers in Java CIS133J Working with Numbers in Java Contents: Using variables with integral numbers Using variables with floating point numbers How to declare integral variables How to declare floating point variables

More information

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet. Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that

More information

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while Pull Lecture Materials and Open PollEv Poll Everywhere: pollev.com/comp110 Lecture 12 else-if and while loops Once in a while Fall 2016 if-then-else Statements General form of an if-then-else statement:

More information

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Big software. code reuse: The practice of writing program code once and using it in many contexts. Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting

More information

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8 Inheritance Notes Chapter 6 and AJ Chapters 7 and 8 1 Inheritance you know a lot about an object by knowing its class for example what is a Komondor? http://en.wikipedia.org/wiki/file:komondor_delvin.jpg

More information

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Array. Array Declaration:

Array. Array Declaration: Array Arrays are continuous memory locations having fixed size. Where we require storing multiple data elements under single name, there we can use arrays. Arrays are homogenous in nature. It means and

More information

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable? Peer Instruction 8 Classes and Objects How can multiple methods within a Java class read and write the same variable? A. Allow one method to reference a local variable of the other B. Declare a variable

More information

DO NOT. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N.

DO NOT. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. CS61B Fall 2013 UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division Test #2 Solutions DO NOT P. N. Hilfinger REPRODUCE 1 Test #2 Solution 2 Problems

More information

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

G52CPP C++ Programming Lecture 9

G52CPP C++ Programming Lecture 9 G52CPP C++ Programming Lecture 9 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture const Constants, including pointers The C pre-processor And macros Compiling and linking And

More information

Inheritance. CSc 372. Comparative Programming Languages. 28 : Ruby Classes. Department of Computer Science University of Arizona.

Inheritance. CSc 372. Comparative Programming Languages. 28 : Ruby Classes. Department of Computer Science University of Arizona. Inheritance CSc 372 Comparative Programming Languages 28 : Ruby Classes Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2011 Christian Collberg Let s start with this,

More information

Programming overview

Programming overview Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in

More information

CSc 372 Comparative Programming Languages

CSc 372 Comparative Programming Languages CSc 372 Comparative Programming Languages 28 : Ruby Classes Christian Collberg Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2011 Christian Collberg November 1, 2011

More information

AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

Chapter 1: A First Program Using C#

Chapter 1: A First Program Using C# Chapter 1: A First Program Using C# Programming Computer program A set of instructions that tells a computer what to do Also called software Software comes in two broad categories System software Application

More information

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSE 142 Su 04 Computer Programming 1 - Java. Objects Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007 Java We will be programming in Java in this course. Partly because it is a reasonable language, and partly because you

More information

Project 5 Due 11:59:59pm Tuesday, April 25, 2017

Project 5 Due 11:59:59pm Tuesday, April 25, 2017 Project 5 Due 11:59:59pm Tuesday, April 25, 2017 Introduction In this project, you will write a compiler for a programming language called Rube, which is a small objectoriented programming language with

More information

do fifty two: Language Reference Manual

do fifty two: Language Reference Manual do fifty two: Language Reference Manual Sinclair Target Jayson Ng Josephine Tirtanata Yichi Liu Yunfei Wang 1. Introduction We propose a card game language targeted not at proficient programmers but at

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Array, Hashes, Code Blocks, Equality 1 Arrays and Hashes Ruby data structures are typically constructed from Arrays and Hashes Built-in syntax for both Each

More information

Topic 7: Algebraic Data Types

Topic 7: Algebraic Data Types Topic 7: Algebraic Data Types 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 5.5, 5.7, 5.8, 5.10, 5.11, 5.12, 5.14 14.4, 14.5, 14.6 14.9, 14.11,

More information

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle Boggle If you are not familiar with the game Boggle, the game is played with 16 dice that have letters on all faces. The dice are randomly deposited into a four-by-four grid so that the players see the

More information

Notes on Chapter Three

Notes on Chapter Three Notes on Chapter Three Methods 1. A Method is a named block of code that can be executed by using the method name. When the code in the method has completed it will return to the place it was called in

More information

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013 1 TYPE CHECKING AND CASTING Lecture 5 CS2110 Spring 2013 1 Type Checking 2 Java compiler checks to see if your code is legal Today: Explore how this works What is Java doing? Why What will Java do if it

More information

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4 Structural Programming and Data Structures Winter 2000 CMPUT 102: Inheritance Dr. Osmar R. Zaïane Course Content Introduction Objects Methods Tracing Programs Object State Sharing resources Selection Repetition

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Software and Programming 1

Software and Programming 1 Software and Programming 1 Lab 1: Introduction, HelloWorld Program and use of the Debugger 17 January 2019 SP1-Lab1-2018-19.pptx Tobi Brodie (tobi@dcs.bbk.ac.uk) 1 Module Information Lectures: Afternoon

More information

Decaf Language Reference Manual

Decaf Language Reference Manual Decaf Language Reference Manual C. R. Ramakrishnan Department of Computer Science SUNY at Stony Brook Stony Brook, NY 11794-4400 cram@cs.stonybrook.edu February 12, 2012 Decaf is a small object oriented

More information

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar Java Classes Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information