11/17/14 ¡ 1 ¡
CSCI-2325 Object-Oriented Paradigm: Ruby
Mohammad T . Irfan
Imperative vs. object-
- riented paradigms
Imperative vs. object- oriented paradigms 1 11/17/14 - - PDF document
11/17/14 CSCI-2325 Object-Oriented Paradigm: Ruby Mohammad T . Irfan Imperative vs. object- oriented paradigms 1 11/17/14 Imperative vs. object-oriented u Imperative u Procedural decomposition u Procedures are all
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
u Learn the basics of Ruby today u Investigate Ruby’s object-oriented design
u Ruby on Rails for web programming
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 3 http://www.aptana.com/
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
u Designed by Yukihiro Matsumoto (Matz) in
u Inspired by Perl and Python
u Less scripting than Perl u More object-oriented than Python u Happy experience!
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
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 keywords. I just want to concentrate on the task. That's the basic idea. So I have tried to make Ruby code concise and succinct.
(http://www.artima.com/intv/ruby.html)
u http://vimeo.com/52954702
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!
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”, 2014]
x.class x.class.methods x.include? “NBA” x.include? “2010”
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
u Creation, insertion, deletion
u myArray = [“NFL”, “NBA”, 2013] u myString = myArray.join(“ ”) #outputs “NFL NBA 2013” u left = myArray.shift #left has value “NFL” u myArray #myArray is now [“NBA”, 2013] u myArray.push(“MLS”) #myArray is now [“NBA”, 2013,
“MLS”]
u myArray.unshift(“NFL”)
#myArray is now [“NFL”, “NBA”, 2013, “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| print item, "--"} #iterate through
items
u myArray.each_index {|i| print i, “->”, myArray[i], “\n”}
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
u From Wikipedia
http://en.wikipedia.org/wiki/Collatz_conjecture
u Take any natural number n. The conjecture is
that no matter what n is, you will always eventually reach 1.
u Take n as input from user.
u If n is even, divide it by 2 to get n/2. If n is odd,
multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process until you reach n = 1. (conditional statements and loops)
u Print all these numbers to a file.
u The number of numbers is called the cycle length
u Output the cycle length (to standard output)
cycle_length = 0
u Purely object oriented u Classes and objects are dynamic u Class can be defined later, dynamically
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
Check out: rubular.com
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
u Can add a method to an existing class
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.
Website .rb
u We can create classes dynamically (just like
Website .rb
u Modify the Website class dynamically
Website.rb (After the previous code that defines the Website class)
u Singleton method
u Use predefined Singleton module
u A module is a collection of methods, constants u Unlike a class, modules cannot be instantiated u Example: Math
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
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 the code
Inherita nce.rb
u Matz: Single inheritance is good because the
u Mix-in: multiple inheritance in some sense
u Share the behavior, not data
u Building block: module
u Collection of methods and constants
Collision! Mixin.rb
u Matz: “[...] approach of plugging in modules
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
u Create a Twitter developer account and use
u Submit the print-out of search results (not
u Due: Next class (Thursday, Nov 13)
u Crawl the web beginning at www.bowdoin.edu in
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.
u First, install gems package management
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
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:
u http://guides.rubygems.org/command-reference/
SQLite DBMS Ruby on Rails Twitter API Email API
u Examples
u http://sferik.github.io/twitter/
u Full documentation
u http://rdoc.info/gems/twitter/index
u Preparation
u Sign up for Twitter u Sign in with your Twitter account at developer site
u https://dev.twitter.com/apps
Copy and paste from your developer account
u Rate limit exceeded! u Twitter’s rules:
u https://dev.twitter.com/rest/public/rate-limiting
Ruby program that creates database Salary.db
Path to the file Salary.db here
u Ruby on Rails
u Model
u DB and constraints on data
u View
u What users see
u Controller
u Takes user input u Consults with model u Directs the view