CSCI-2320 Object-Oriented Paradigm: Ruby

CSCI-2320 Object-Oriented Paradigm: Ruby

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.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    31 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us