CMSC 330: Organization of Programming Languages Ruby Hash Tables (and other topics)

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Written by: Dr. JJ Shepherd
Generics and the ArrayList Class
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Final Review.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Introduction to Perl. How to run perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Your program/script.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
The Ruby Programming Language
Programming Languages and Paradigms Object-Oriented Programming.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
1 CMSC 330: Organization of Programming Languages Ruby.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Programming in Java CSCI-2220 Object Oriented Programming.
CMSC 330: Organization of Programming Languages Ruby Regular Expressions and other topics.
Introduction to Perl “Practical Extraction and Report Language” “Pathologically Eclectic Rubbish Lister”
Introduction to Generics
Ruby Objects, Classes and Variables CS 480/680 – Comparative Languages.
CMSC330 Summer 2009 Kinga Dobolyi Introduction to Ruby.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Written by: Dr. JJ Shepherd
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
CMSC330 More Ruby. Last lecture Scripting languages Ruby language –Implicit variable declarations –Many control statements –Classes & objects –Strings.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java Programming Language
Java Programming Language
Chapter 11 Inheritance and Polymorphism Part 1
Review for Midterm 3.
Inheritance and Polymorphism
Presentation transcript:

CMSC 330: Organization of Programming Languages Ruby Hash Tables (and other topics)

CMSC 3302 Standard Library: Hash A Hash acts like an associative array or dictionary lookup –Elements can be indexed by any kind of values –Every Ruby object can be used as a hash key, because the Object class has a hash method Elements are referred to using [] like array elements, but Hash.new is the Hash constructor italy["population"] = italy["continent"] = "europe" italy[1861] = "independence"

CMSC 3303 Hash (cont’d) Convenient syntax for creating literal hashes –Use { key => value,... } to create hash table credits = { "cmsc131" => 4, "cmsc330" => 3, } x = credits["cmsc330"] # x now 3 credits["cmsc311"] = 3

CMSC 3304 Hash (cont’d) The Hash method values returns an array of a hash table’s values (in some order) And keys returns an array of a hash table’s keys (in some order) Iterating over a hash: italy.keys.each { |key| puts("key: #{key}, value: #{italy[key]}") } italy.each { |key, value| puts("key: #{key}, value: #{value}") }

Sorting Array and Hash structures can be sorted: [7, 1, 5].sort => [1, 5, 7] Sorting a Hash returns a nested Array, sorted by key: {"bob"=>4, "sue"=>2, "bill"=>7}.sort => [["bill", 7], ["bob", 4], ["sue", 2]] To sort by value, use sort_by and a code block: people = {"bob"=>4,"sue"=>2,"bill"=>7} people.sort_by { |key,value| value } => [["sue", 2], ["bob", 4], ["bill", 7]] CMSC 330

6 Standard Library: File Lots of convenient methods for IO File.new("file.txt", "rw")# open for rw access f.readline # reads the next line from a file f.readlines # returns an array of all file lines f.eof # return true if at end of file f.close # close file f << object# convert object to string and write to f $stdin, $stdout, $stderr # global variables for standard UNIX IO By default stdin reads from keyboard, and stdout and stderr both write to terminal File inherits some of these methods from IO

CMSC 3307 Exceptions Use begin...rescue...ensure...end –Like try...catch...finally in Java begin f = File.open("test.txt", "r") while !f.eof line = f.readline puts line end rescue Exception => e puts "Exception:" + e.to_s + " (class " + e.class.to_s + ")” ensure f.close end Class of exception to catch Local name for exception Always happens

CMSC 3308 Practice: Amino Acid counting in DNA Write a function that will take a filename and read through that file counting the number of times each group of three letters appears so these numbers can be accessed from a hash. (assume: the number of chars per line is a multiple of 3) gcggcattcagcacccgtatactgttaagcaatccagatttttgtgtataacataccggc catactgaagcattcattgaggctagcgctgataacagtagcgctaacaatgggggaatg tggcaatacggtgcgattactaagagccgggaccacacaccccgtaaggatggagcgtgg taacataataatccgttcaagcagtgggcgaaggtggagatgttccagtaagaatagtgg gggcctactacccatggtacataattaagagatcgtcaatcttgagacggtcaatggtac cgagactatatcactcaactccggacgtatgcgcttactggtcacctcgttactgacgga

CMSC 3309 Practice: Amino Acid counting in DNA def countaa(filename) file = File.new(filename, "r") arr = file.readlines hash = Hash.new arr.each{ |line| acids = line.scan(/.../) acids.each{ |aa| if hash[aa] == nil hash[aa] = 1 else hash[aa] += 1 end } end initialize the hash, or you will get an error when trying to index into an array with a string get the file handle array of lines from the file for each line in the file for each triplet in the line get an array of triplets in the line

Global Variables in Ruby Ruby has two kinds of global variables –Class variables beginning with –Global variables across classes beginning with $ 10 class Global = 0 def Global.inc = + 1; $x = $x + 1 end def Global.get return end $x = 0 Global.inc $x = $x + 1 Global.inc puts(Global.get) puts($x) define a class (“singleton”) method

Special Global Variables Ruby has a bunch of global variables that are implicitly set by methods The most insidious one: $_ –Default method return, argument in many cases –Can lead to shorter programs, but more confusion More useful ones: $1, $2, $3, etc. –Matches from regular expressions (=~ or !~) $0 is the name of the Ruby script 11 gets # implicitly reads input into $_ print # implicitly writes $_

CMSC 330: Organization of Programming Languages Ruby Objects and Inheritance

Classes and Objects Class names begin with an uppercase letter The “new” method creates an object –s = String.new creates a new String and makes s refer to it Every class inherits from Object 13

Everything is an Object In Ruby, everything is in fact an object –(-4).abs integers are instances of Fixnum –3 + 4 infix notation for “invoke the + method of 3 on argument 4” –"programming".length strings are instances of String –String.new classes are objects with a new method –(4.13).class use the class method to get the class for an object floating point numbers are instances of Float 14

Objects and Classes Objects are data Classes are types of data But in Ruby, classes themselves are objects! Fixnum, Float, String, etc., (including Class), are objects of type Class ObjectClass 10Fixnum -3.30Float “CMSC 330”String String.newString FixnumClass StringClass

Two Cool Things to Do with Classes Since classes are objects, you can manipulate them however you like if p then x = String else x = Time end # Time is... # another class y = x.new # creates a String or a Time, # depending upon p You can get names of all the methods of a class –Object.methods => ["send", "name", "class_eval", "object_id", "new", "autoload?", "singleton_methods",... ] 16

The nil Object Ruby uses a special object nil –All uninitialized fields set to nil refers to a class field) => nil –Like NULL or 0 in C/C++ and null in Java nil is an object of class NilClass –It’s a singleton object – there is only one instance of it NilClass does not have a new method –nil has methods like to_s, but not other methods that don’t make sense + 2 NoMethodError: undefined method `+' for nil:NilClass 17

What is a Program? In C/C++, a program is... –A collection of declarations and definitions –With a distinguished function definition int main(int argc, char *argv[]) {... } –When you run a C/C++ program, it’s like the OS calls main(...) In Java, a program is... –A collection of class definitions –With a class Cl that contains a method public static void main(String[] args) –When you run java Cl, the main method of class Cl is invoked 18

A Ruby Program is... The class Object –When the class is loaded, any expressions not in method bodies are executed 19 def sayN(message, n) i = 0 while i < n puts message i = i + 1 end return i end x = sayN("hello", 3) puts(x) invokes self.sayN

Ruby is Dynamically Typed Recall we don’t declare types of variables –But Ruby does keep track of types at run time x = 3; x.foo NoMethodError: undefined method 'foo' for 3:Fixnum We say that Ruby is dynamically typed –Types are determined and checked at run time Compare to C, which is statically typed 20 # Ruby x = 3 x = "foo" # gives x a # new type /* C */ int x; x = 3; x = "foo"; /* not allowed */

Types in Java and C++ Are Java and C++ statically or dynamically typed? –A little of both –Many things are checked statically Object x = new Object(); x.println(“hello”); // No such method error at compile time –But other things are checked dynamically Object o = new Object(); String s = (String) o; // No compiler warning, fails at run time // (Some Java compilers may be smart enough to warn about above cast) 21

Tradeoffs: Static vs. Dynamic Ease of coding Error-proneness Usefulness of type checking

Classes and Objects in Ruby 23 class Point def initialize(x, = = y end def += x end def to_s return "(" + "," + ")" end p = Point.new(3, 4) p.addX(4) puts(p.to_s) constructor definition class contains method/ constructor definitions instance variables prefixed with method with no arguments instantiation invoking no-arg method

Notes Parentheses are optional for method calls Ruby does not support method overloading –There can only be one initialize method –The last initialize method defined is used 24

Classes and Objects in Ruby (cont’d) Recall classes begin with an uppercase letter inspect converts any instance to a string irb(main):033:0> p.inspect => "# " Instance variables are prefixed –Compare to local variables with no prefix –Cannot be accessed outside of class The to_s method can be invoked implicitly –Could have written puts(p) Like Java’s toString() methods 25

Inheritance Recall that every class inherits from Object 26 class A def plusplus(x) return x + 1 end class B < A def plusplus(y) return (super(y) + 1) end b = B.new puts(b.plusplus(3)) extend superclass invoke plusplus method of parent What is the output?

super() in Ruby Within the body of a method, a call to super acts just like a call to that original method, except that the search for a method body starts in the superclass. 27

Inheritance (cont’d) Ruby uses single inheritance; i.e. each class may only have a single parent: class A < B (B is the parent of A) A.superclass (returns B)

Inheritance (cont’d) Ruby supports mixins and modules, which are similar to Java interfaces (modules cannot be instantiated): module M1module M2 def f1def f2endend class A include M1 include M2 end Modules can be mixed in to particular object instances during execution: obj = “test” obj.extend M1 class A will have both f1 and f2 obj will have f1

Single vs. Multiple Inheritance Single inheritance: one parent per class Multiple inheritance: unlimited parents per class “Diamond problem” –If B and C both override method foo() in A, which version is called by D? –In what order are constructors called? Three ways to fix: –Explicit namespacing –Linear prioritization –Non-instantiation of superclasses D CB A