31
4/22/20 1 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

CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

1

CSCI-2320Object-Oriented Paradigm: Ruby

Mohammad T. Irfan

1

Ruby resources

u Installation– see class website

u Learningu 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

Page 2: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

2

Origin

u Designed by Yukihiro Matsumoto (Matz) in early 1990s

u Inspired by Perl and Pythonu Less scripting than Perl

u More object-oriented than Python

u Happy experience!

3

Quotesu 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

Page 3: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

3

Interview of Matz

u http://vimeo.com/52954702

5

Features

u Purely object orientedu Every data value is an object – no primitive typeu Every subroutine is a methodu Inheritance can be applied to any class

u Both classes and objects are dynamic!u Can add methods to classes and objects dynamicallyu Different objects of the same class can behave

differently

u Dynamically typedu Static scoping

u 37 reasons to love Ruby!u https://www.bowdoin.edu/~mirfan/Ruby37.html

You should be able to explain these!

6

Page 4: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

4

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 irbu x = 10

if x % 2 == 0puts “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.classx.class.methodsx.include? “NBA”x.include? 200

8

Page 5: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

5

Variables

u Type is implicitu Type can be changed dynamicallyu Naming starts with:

u Examples (in irb)u x = 10.99

x.class #prints Floatx = “Hello Ruby!”x.class #prints String

u Very rich String classu Examples: https://ruby-doc.org/core-2.6/String.html

$ Global variable

@ Instance variable

[a-z] or _ Local variable

[A-Z]Constant (only first letter needs to be uppercase)

9

Arrays (mutable)

u Creation, insertion, deletionu 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 itemsu myArray.each_index {|i| print i, “->”, myArray[i], “\n”}

10

Page 6: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

6

Coding in Ruby with VS Codeu 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

u Ways to run u 1. Add this line at the end of source.rb and run it

without debuggingu 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 == 01

elsen * fact(n-1)

end end

12

Page 7: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

7

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

Page 8: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

8

Solution

15

16

Page 9: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

9

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 Conditionalu if – elsif – else – end

u ---- if condition

u Iterationu Usual while loops

u arrayName.each do |item|...end

u arrayName.each { |item| ...}

u Other ways: for loopfor i in 0..4...end

18

Page 10: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

10

Cool stuff:Reading a website

19

20

Page 11: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

11

More fun:Can we “crawl” the

web?1. Extract all links from a web page2. Do recursion [Assignment—later]

21

Check out:rubular.com

22

Page 12: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

12

“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

Page 13: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

13

Open class

u Can add a method to an existing class

class Arraydef summarize

self.each do |x|print x, " "

end #iteratorprint "\n"

end #defend #class

25

Open class

example

26

Page 14: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

14

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

Page 15: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

15

Instance variables and permissionsclass Animal

attr_reader :name #delete this and seedef initialize(animal_name)

@name = animal_nameend

end

a = Animal.new("dog")b = Animal.new("cat")

#How can we do the following?#a.name = "horse"

puts a.nameputs b.name

u No declaration needed

u Dynamically appended to object when it’s first referenced (even if the constructor doesn’t reference it)

u Permission levels: attr_reader, attr_writer, attr_accessor

u Contrast: Java, Python

29

Website.rb

30

Page 16: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

16

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

Page 17: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

17

Modifying a class

u Modify the Website class dynamicallyWebsite.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

Page 18: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

18

CP 6

u Submit your practice codes on Blackboardu 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

Page 19: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

19

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

Page 20: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

20

Inheritance: cool stuff!

u Mix-in: multiple inheritance in some senseu Share the behavior, not data

u Building block: moduleu Collection of methods and constants

u Unlike a class, modules cannot be instantiated

u Example: Math

39

Mix-in examplemodule A

PI = 3.14E = 2.718def printPI

puts PIenddef printE

puts Eend

end

module BPI = 3.14159def printPI

puts PIend

end

class C #mix-in classinclude Ainclude B

endc = C.newc.printPI #=> 3.14159c.printE #=> 2.718Collision!

Mixin.rb

40

Page 21: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

21

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 astrict 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 patternu What’s singleton design pattern? (popular job interview Q)

https://en.wikipedia.org/wiki/Singleton_patternu Use predefined Singleton module

require 'Singleton'

class SingletonClass

include Singleton #include module# ...

end

a = SingletonClass.instanceb = SingletonClass.instancea == b #=> truec = SingletonClass.new #=> NoMethodError

# new is private

43

Page 22: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

22

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 includeu 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

Page 23: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

23

WebMixin.rb

46

47

Page 24: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

24

CP 7

u Submit your practice codes on Blackboardu 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 GemsTwitter

SQLite Database

51

Page 25: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

25

Installing new gems

u Commandu 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

53

Working with the Twitter gem

u Examplesu http://sferik.github.io/twitter/

u Full documentationu http://rdoc.info/gems/twitter/index

54

Page 26: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

26

Working with the Twitter gem

u Preparationu 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

Page 27: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

27

57

58

Page 28: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

28

59

Working with the Twitter gem

Copy and paste from your developer account

60

Page 29: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

29

Common problem

u Rate limit exceeded!

u Twitter’s rules:u https://dev.twitter.com/rest/public/rate-limiting

61

Store search results in database

62

Page 30: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

30

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

Page 31: CSCI-2320 Object-Oriented Paradigm: Ruby - Bowdoin College › ~mirfan › slides › 2020 Spring › PL... · 2020-04-22 · 4/22/20 2 Origin uDesigned by Yukihiro Matsumoto (Matz)

4/22/20

31

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 tutorialu http://www.w3schools.com/sql/default.asp

67

Coming up next

u Ruby on Railsu 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