4/22/20
CSCI-2320 Object-Oriented Paradigm: Ruby
Mohammad T. Irfan
1
Ruby resources
u Installation– see class website u Learning
u http://ruby-doc.org/ u English translation of the creator’s user guide (by Mark Slagell)
u https://ruby-doc.org/docs/ruby-doc- bundle/UsersGuide/rg/
u Other good reference
u http://www.tutorialspoint.com/ruby/
u Interactive tutorial using only your web-browser
u https://try.ruby-lang.org/
2
1 4/22/20
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!
3
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. (https://ruby.fandom.com/wiki/Ruby) 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)
4
2 4/22/20
Interview of Matz
u http://vimeo.com/52954702
5
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 You should be able to explain these! u Static scoping
u 37 reasons to love Ruby! u https://www.bowdoin.edu/~mirfan/Ruby37.html
6
3 4/22/20
Let’s code in Ruby
7
Before we start
u If you want to quickly check something without writing a program u Use the irb command in Terminal u Examples in irb 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
8
4 4/22/20
Variables
u Type is implicit u Type can be changed dynamically u Naming starts with:
$ Global variable @ Instance variable [a-z] or _ Local variable Constant (only first letter [A-Z] needs to be uppercase)
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: https://ruby-doc.org/core-2.6/String.html
9
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”}
10
5 4/22/20
Coding in Ruby with VS Code
u Set up Ruby extension u Click on the Extension icon u Type Ruby in search box u Install “Ruby Language Support” by Peng Lv (the first that appears in search) u Make a folder in your computer for Ruby codes u VS Code à File à Open, browse to the folder you just created, and click Open u Click on the new file icon to create a Ruby source file with .rb extenstion u VS Code à Run à Open Configurations: Select “Ruby”; then select “Debug Local File” Replace main.rb with your Ruby file name in the launch.json file 11
Sample program: factorial
u Save it as source.rb
def fact(n) if n == 0 1 else n * fact(n-1) end end
u Ways to run u 1. Add this line at the end of source.rb and run it without debugging u puts fact(10) u 2. ruby -I ./ -r source.rb -e "puts fact(10)” u Command line arguments are also supported
12
6 4/22/20
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
13
# of steps (y) vs. input number (x)
14
7 4/22/20
Solution
15
16
8 4/22/20
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
17
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
18
9 4/22/20
Cool stuff: Reading a website
19
20
10 4/22/20
More fun: Can we “crawl” the web? 1. Extract all links from a web page 2. Do recursion [Assignment—later]
21
Check out: rubular.com
22
11 4/22/20
“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
23
Object-oriented features
24
12 4/22/20
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
25
Open class example
26
13 4/22/20
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 of dynamic features, such as adding methods to objects, is meta-programming. Such features allow you to create a library that adapts to the environment, but they are not for casual uses.
27
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
28
14 4/22/20
Instance variables and permissions
class Animal attr_reader :name #delete this and see def initialize(animal_name) @name = animal_name end u No declaration needed end u Dynamically appended to object when it’s first a = Animal.new("dog") referenced (even if the b = Animal.new("cat") constructor doesn’t reference #How can we do the following? it) #a.name = "horse" u Permission levels: attr_reader, attr_writer, puts a.name attr_accessor puts b.name u Contrast: Java, Python
29
Website .rb
30
15 4/22/20
Classes in Ruby: surprise!
Yes, classes are objects of Class
What does it mean?
31
u We can create classes dynamically (just like any other object)
32
16 4/22/20
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)
Q. How does @is_pdf work? Q. What is =~?
33
Modify a specific object dynamically! (Not the whole class)
u Singleton method
34
17 4/22/20
CP 6
u Submit your practice codes on Blackboard u Practice codes given in the slides u Up to this slide u If you have multiple source files, submit all u Due: Wednesday, April 22 u Collaboration Level: 0 (no restrictions) https://turing.bowdoin.edu/dept/collab.php u Work in groups
35
Inheritance
36
18 4/22/20
Inheritance: the usual stuff
Website .rb
37
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.”
38
19 4/22/20
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
39
Mix-in example Mixin.rb module A module B PI = 3.14 PI = 3.14159 E = 2.718 def printPI def printPI puts PI puts PI end end end def printE puts E class C #mix-in class end include A end include B end c = C.new c.printPI #=> 3.14159 Collision! c.printE #=> 2.718
40
20 4/22/20
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 inheritance. In fact, a mix-in is actually a 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.”
41
Another example of modules: Singleton design pattern
u What’s singleton design pattern? (popular job interview Q) https://en.wikipedia.org/wiki/Singleton_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
43
21 4/22/20
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
44
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
45
22 4/22/20
WebMixin .rb
46
47
23 4/22/20
CP 7
u Submit your practice codes on Blackboard u From inheritance to this slide u If you have multiple source files, submit all u Optional: do the rest of the slides beginning from the next slide u Due: Wednesday, April 29 u Collaboration Level: 0 (no restrictions) https://turing.bowdoin.edu/dept/collab.php u Work in groups
50
Ruby Gems Tw i t t e r SQLite Database
51
24 4/22/20
Installing new gems
u Command u gem install twitter Tw i t t e r A P I
u gem install mail Email API u Other gems we will need later:
u gem install sqlite3 SQLite DBMS
u gem install rails Ruby on Rails
u Useful commands: gem uninstall ..., gem list ..., etc.
u http://guides.rubygems.org/command-reference/
53
Working with the Twitter gem
u Examples u http://sferik.github.io/twitter/ u Full documentation
u http://rdoc.info/gems/twitter/index
54
25 4/22/20
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
55
This interface may have changed!
56
26 4/22/20
57
58
27 4/22/20
59
Working with the Twitter gem
Copy and paste from your developer account
60
28 4/22/20
Common problem
u Rate limit exceeded! u Tw i t t e r’s r u l e s :
u https://dev.twitter.com/rest/public/rate-limiting
61
Store search results in database
62
29 4/22/20
Creating Sqlite3 database using Ruby
Ruby program that creates database Salary.db
65
Accessing Salary.db from terminal (outside of Ruby)
Path to the file Salary.db here
66
30 4/22/20
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
67
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
68
31