11/14/17 1
CSCI-2320 Object-Oriented Paradigm: Ruby
Mohammad T . Irfan
Imperative vs. object-
- riented paradigms
Imperative vs. object- oriented paradigms 1 11/14/17 Imperative - - PDF document
11/14/17 CSCI-2320 Object-Oriented Paradigm: Ruby Mohammad T . Irfan Imperative vs. object- oriented paradigms 1 11/14/17 Imperative vs. object-oriented u Imperative u Procedural decomposition u Procedures are all powerful u Data is
11/14/17 1
Mohammad T . Irfan
11/14/17 2
Imperative vs. object-oriented
u Imperative
u Procedural decomposition u Procedures are all powerful u Data is helpless, at the mercy of procedures
u Object-oriented (OO)
u Data-centric: data governs the decomposition u Classes – templates/patterns, abstracts away data u Objects – actual things/instantiations of classes
u Advantages of OO paradigm
u Collaboration u Debugging u Reuse
Roadmap
u OOP principles u Learn the basics of Ruby u Investigate Ruby’s object-oriented design
principles
u Ruby on Rails for web programming
11/14/17 3
Examples: Java
OOP principles
These principles typically interact with one another.
11/14/17 4
u Hide internal representation of data by
providing methods (e.g., getter and setter methods; other methods that work on data)
u Benefits: decoupling data and functionality,
protection of data, hiding unnecessary details on representation
Encapsulation example: Book class
u Want a class for representing certain
information about a book
u Note: each object is one single book u Multiple objects à many books
book?
can apply on book data?
u Encapsulation: bind the above two together u Sample code:
u http://www.javaworld.com/article/2979739/
learn-java/java-101-classes-and-objects-in- java.html
11/14/17 5
11/14/17 6
A tale of two cities 1859 Moby Dick 1851 Unknown
book1 book2 book3 Shared class variable: count = 3 Methods are also shared
11/14/17 7
Encapsulation question
u Build on the Book class to include author
authors?
u Allows one class to "inherit" the methods
(functionalities) and attributes (variables) of another class
u Subclass (AKA derived class)
extends (or inherits) Superclass (AKA base class)
u Java's keyword: extends
11/14/17 8 Subclass of subclass variables and methods
Inheritance in picture
u Hierarchical organization
Subclass variables and methods
Superclass variables and methods
Inheritance in Java
Subclass Multiple superclasses Superclass Multiple subclasses Chain of inheritance
11/14/17 9
11/14/17 10
Chain of inheritance (Multilevel inheritance)
u New class for shipping a box, inherits
WeightedBox
Demo
11/14/17 11
u The ability of an object to take many forms
u Compare with method overloading
u This is achieved via inheritance
u Note the inter-relation
u Superclass can refer to subclass object u Concept: method overriding
Method overriding
u Subclass re-defines a superclass method with
the same method signature
u Next few slides
u PlainBox class models a simple 3D box u WeightedBox class extends PlainBox class
u Adds weight variable u Overrides the multiply method
u BoxDemo class gives a demo
11/14/17 12
Superclass' multiply method is hidden from the subclass unless the subclass explicitly calls it using super
11/14/17 13 Output
u Generalization u Examples
u C (not OOP): qsort works with different data types u C++: STL u Java: Abstract class allows generalization by hiding
implementation details
11/14/17 14
Encapsulation vs abstraction
u Debates on orthogonality of concepts u http://www.tonymarston.co.uk/php-mysql/
abstraction.txt
u Roughly– information/representation hiding
(capsule) vs implementation hiding (generalization)
11/14/17 15
Ruby Installation
u Several ways to install, as described here:
https://www.ruby-lang.org/en/downloads/
u Mac/Linux: Use RVM (https://rvm.io/rvm/install)
u Command line$ \curl -sSL https://get.rvm.io | bash -s
stable –ruby
u Then, follow the instruction given in terminal u To test, commands are:
u ruby –v u rvm –v
u If you get errors, run the following commands (assuming
2.1.4 is the latest version—look up rvm website for it)
u brew update && brew upgrade u rvm reinstall 2.1.4 --disable-binary
u Windows: Install Ruby 2.0.0 from RubyInstaller.org
http://rubyinstaller.org/downloads/
u Recommended IDE
u Aptana Studio http://www.aptana.com/
Ruby resources
u Learning
u English translation of the creator’s user guide (by
Mark Slagell)
u http://www.rubyist.net/~slagell/ruby/index.html
u Go to reference
u Documentation: http://ruby-doc.org/core-2.0.0/ u http://www.tutorialspoint.com/ruby/
u Interactive tutorial using only your web-browser
u http://tryruby.org
11/14/17 16
Origin
u Designed by Yukihiro Matsumoto (Matz) in
early 1990s
u Inspired by Perl and Python
u Less scripting than Perl u More object-oriented than Python u Happy experience!
Quotes
u Bruce Stewart (2001): Did you have a guiding philosophy
when designing Ruby?
u Matz: Yes, it's called the "principle of least surprise." I believe
people want to express themselves when they program. They don't want to fight with the language. Programming languages must feel natural to programmers. I tried to make people enjoy programming and concentrate on the fun and creative part of programming when they use Ruby.
(http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html)
u Bill Venners (2003): In an introductory article on Ruby, you
wrote, "For me the purpose of life is partly to have joy. Programmers often feel joy when they can concentrate on the creative side of programming, So Ruby is designed to make programmers happy." How can Ruby make programmers happy?
u Matz: You want to enjoy life, don't you? If you get your job done
quickly and your job is fun, that's good isn't it? That's the purpose of life, partly. Your life is better. I want to solve problems I meet in the daily life by using computers, so I need to write programs. By using Ruby, I want to concentrate the things I do, not the magical rules of the language, like starting with public void something something something to say, "print hello world." I just want to say, "print this!" I don't want all the surrounding magic
(http://www.artima.com/intv/ruby.html)
11/14/17 17
Interview of Matz
u http://vimeo.com/52954702
Features
u Purely object oriented
u Every data value is an object – no primitive type u Every subroutine is a method u Inheritance can be applied to any class
u Both classes and objects are dynamic!
u Can add methods to classes and objects dynamically u Different objects of the same class can behave
differently
u Dynamically typed u Static scoping u 37 reasons to love Ruby!
u http://rubyhacker.com/ruby37.html
You should be able to explain these!
11/14/17 18
Before we start
u If you want to quickly check something without
writing a program
u Use the irb command in Terminal
u Examples
u x = 10
if x % 2 == 0 puts “Even” else puts “Odd” end
u What does nil mean in the output? In Ruby, there is
no statement. Everything is an expression returning a value, whether you explicitly say return or not.
u x = [“NFL”, “NBA”, 100]
x.class x.class.methods x.include? “NBA” x.include? 200
11/14/17 19
Variables
u Type is implicit u Type can be changed dynamically u Naming: u Examples (in irb)
u x = 10.99
x.class #prints Float x = “Hello Ruby!” x.class #prints String
u Very rich String class
u Examples: http://ruby-doc.org/core-2.0.0/String.html
$ Global variable @ Instance variable [a-z] or _ Local variable [A-Z] Constant
Arrays (mutable)
u Creation, insertion, deletion
u myArray = [“NFL”, “NBA”, 100] u myString = myArray.join(“ ”) #outputs “NFL NBA 100” u left = myArray.shift #left has value “NFL” u myArray #myArray is now [“NBA”, 100] u myArray.push(“MLS”) #myArray is now [“NBA”, 100,
“MLS”]
u myArray.unshift(“NFL”)
#myArray is now [“NFL”, “NBA”, 100, “MLS”]
u delete(obj), delete_at(index), delete_if { |item|
block }
u Accessing elements
u myArray[0] #“NFL” u myArray[0..-1] #everything in the array u myArray.each {|item| puts item} #iterate through items u myArray.each_index {|i| print i, “->”, myArray[i], “\n”}
11/14/17 20
Sample program: factorial
u Save it as source.rb u Ways to run
u 1. Add this line at the end of source.rb and click on
run
u puts fact(10)
u 2. ruby -I ./ -r source.rb -e "puts fact(10)” u Command line arguments are also supported
def fact(n) if n == 0 1 else n * fact(n-1) end end
Problem: Collatz Conjecture
u From Wikipedia
http://en.wikipedia.org/wiki/Collatz_conjecture
u Take any integer n > 0 as input. The conjecture is
that no matter what n is, you will always eventually reach 1 if you follow this procedure:
u If n is even, assign n = n/2. If n is odd, assign n =
3n + 1. Repeat the process until you reach n = 1 (conditional statements and loops)
u (Extra job) Print all these numbers to a file
u The # of steps is called the cycle length of n
u Output the cycle length (to standard output) u (Extra job) Also write it to the file
11/14/17 21
# of steps (y) vs. input number (x)
Solution
11/14/17 22
Review: What’s new in Ruby? (vs. Java/C++)
u Purely object oriented u Classes and objects are dynamic u Class can be defined later, dynamically
11/14/17 23
Control structure
u Conditional
u if – elsif – else – end u ---- if condition
u Iteration
u Usual while loops u arrayName.each do |item|
... end
u arrayName.each { |item| ...} u Other ways: for loop
for i in 0..4 ... end
11/14/17 24
11/14/17 25
Check out: rubular.com
“Gem” for crawling the web
u Example: anemone http://anemone.rubyforge.org/
u Uses another gem called nokogiri for parsing web pages
u Command line: $ gem install anemone u Ruby Code: require 'anemone' Anemone.crawl("http://www.Bowdoin.edu/") do |anemone| anemone.on_every_page do |page| puts page.url end end
11/14/17 26
Open class
u Can add a method to an existing class
class Array def summarize self.each do |x| print x, " " end #iterator print "\n" end #def end #class
11/14/17 27 Open class example
In Matz’s words... [Artima]
u Bill Venners: In Ruby, I can add methods and
variables to objects at runtime. ... But in Java, for example, once a class is loaded or an object is instantiated, its interface stays the same. Allowing the interface to change at runtime seems a bit scary to me. ... What's the benefit of being able to add methods at runtime?
u Yukihiro Matsumoto: First of all, you don't have
to use that feature. The most useful application
allow you to create a library that adapts to the environment, but they are not for casual uses.
11/14/17 28
Naming rules
Starts with Category of variable $ Global variable @ Instance variable @@ Class variable [a-z] or _ Local variable [A-Z] Constant
Next: Classes in Ruby – the usual stuff
Website .rb
11/14/17 29
Classes in Ruby: surprise!
Yes, classes are
Class
What does it mean?
u We can create classes
dynamically (just like any other object)
11/14/17 30
Modifying a class
u Modify the Website class dynamically
Website.rb (After the previous code that defines the Website class and creates an object of it)
Modify a specific object dynamically! (Not the whole class)
u Singleton method
11/14/17 31
Inheritance: the usual stuff
Website .rb
11/14/17 32
No multiple inheritance
u Matz: Single inheritance is good because the
whole class inheritance structure forms a single tree with a single root, named Object, and that is very easy to understand. In languages with multiple inheritance, the classes form a network, which is harder to understand.
Inheritance: cool stuff!
u Mix-in: multiple inheritance in some sense
u Share the behavior, not data
u Building block: module
u Collection of methods and constants u Unlike a class, modules cannot be instantiated u Example: Math
11/14/17 33
Mix-in example
module A PI = 3.14 E = 2.718 def printPI puts PI end def printE puts E end end module B PI = 3.14159 def printPI puts PI end end class C #mix-in class include A include B end c = C.new c.printPI #=> 3.14159 c.printE #=> 2.718
Collision! Mixin.rb
Matz on Mix-ins
u Matz: “[...] approach of plugging in modules
is called Mix-ins. Mix-ins originally started in LISP culture as a usage of multiple
strict way of using multiple inheritance. So in LISP , it's a style of using multiple inheritance. In Ruby, we force you to use mix-ins by supporting classes and modules.”
11/14/17 34
Another example of modules: Singleton design pattern
u Use predefined Singleton module
require 'Singleton' class SingletonClass include Singleton #include module # ... end a = SingletonClass.instance b = SingletonClass.instance a == b #=> true c = SingletonClass.new #=> NoMethodError # new is private
load vs. include vs. require
u load 'open-uri.rb'
u Must mention .rb u Can load the same library files multiple times
u require 'open-uri'
u No .rb u Loads a library only once– prevents multiple
loading u include
u Used for including modules within a class u Like copying and pasting code (not file)—within a
class or module
11/14/17 35
Mix-in: more cool stuff!
u Modules do not have states – why? u But... it can fake it!
u Example on the next slide: Personal website
subclasses Website and includes a module called PersonalInformation
WebMixin .rb
11/14/17 36
Assignment (Due on Tue, Nov 21)
u Crawl the web beginning at www.bowdoin.edu in
an object-oriented way and detect broken links
u Define necessary classes (and modules if needed) u Recursion is the key
u Example: www.bowdoin.edu has a link to
www.bowdoin.edu/computer-science, which has a broken link www.bowdoin.edu/~who. To detect the broken link, you will have to recursively fetch web pages and check links therein.
u Confine your program to the Bowdoin domain. u Caution: it will take a really long time. So, do not re-
check the same link.
11/14/17 37
Assignment
u Special cases
u http://www.bowdoin.edu/news u Currently there's some non-UTF8 characters u webpage.scan("...").flatten will generate
exception
u Handle that exception gracefully (that is, just ignore
the content of http://www.bowdoin.edu/news
u Make sure your program works on the testbed u It's a good idea to also test using
http://www.bowdoin.edu/computer-science
Twitter—Class Participation HW SQLite Database
11/14/17 38
Installation
u First, install gems package management
system
pages/download
u Extract it u Go into the extracted folder where you can see
the "setup.rb" file
u Execute this command:
u ruby setup.rb
u
Execute this command: gem update --system
Installing new gems
u Command
u gem install twitter u gem install mail
u Other gems we will need later:
u gem install sqlite3 u gem install rails
u Useful commands:
gem uninstall ..., gem list ..., etc.
u http://guides.rubygems.org/command-reference/
SQLite DBMS Ruby on Rails Twitter API Email API
11/14/17 39
Working with the Twitter gem
u Examples
u http://sferik.github.io/twitter/
u Full documentation
u http://rdoc.info/gems/twitter/index
Working with the Twitter gem
u Preparation
u Sign up for Twitter u Sign in with your Twitter account at developer site
u https://dev.twitter.com/apps
11/14/17 40
11/14/17 41
11/14/17 42
Working with the Twitter gem
Copy and paste from your developer account
Common problem
u Rate limit exceeded! u Twitter’s rules:
u https://dev.twitter.com/rest/public/rate-limiting
11/14/17 43
Store search results in database
Class Participation HW Do in groups
u Create a Twitter developer account and use
the Twitter API (see the previous slides) to search Twitter.
u New: need to enter your cell phone number
u Enter the search results into a database (the
previous slide).
u Submit a print-out of all the output of your
program (do not submit code—it contains personal information).
u Due: Next class
11/14/17 44
Creating Sqlite3 database using Ruby
Ruby program that creates database Salary.db
Accessing Salary.db from terminal (outside of Ruby)
Path to the file Salary.db here
11/14/17 45
A few other useful SQL commands
u delete from SalaryTable where name="Alice";
u Deletes only those rows where the name is Alice u You can specify complex conditions using and/or
u delete from SalaryTable;
u Deleles all rows from that table
u drop table SalaryTable;
u Deletes the SalaryTable itself u Both the schema and the contents will be gone
u Best tutorial
u http://www.w3schools.com/sql/default.asp
Coming up next
u Ruby on Rails
u Web programming platform built using Ruby u Model
u DB and constraints on data
u View
u Generates what users see
u Controller
u Takes user input u Consults with model u Directs the view