ruby - os3 to ruby • ruby is "an interpreted scripting language for quick and easy...

90
Ruby ES 2013/2014 Adam Belloum [email protected] Mikołaj Baranowski [email protected] Material Prepared by Eelco Schatborn

Upload: trinhngoc

Post on 11-Apr-2019

242 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Ruby

ES 2013/2014Adam [email protected]łaj [email protected]

Material Prepared by Eelco Schatborn

Page 2: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

ES: Ruby

• Today:1.Ruby introduction2.Basic Ruby: types, variables, statements, methods3.Regular expression4.File and I/O5.Modules6.Packages7.Object Oriented Ruby8.Documentation9.Examples 10.Assignments

Page 3: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Introduction to Ruby

• Ruby was created by Yukihiro Matsumoto a.k.a. “Matz”• Introduced in 1994• Officially released by Matsumoto in

1995.• “Ruby” was named as a gemstone as a

joke. . .• The TIOBE index, which measures the

growth of programming languages, ranks Ruby as #13 among programming languages worldwide (2013)

“trying to make Ruby natural, not simple,”

“Ruby is simple in appearance, but is very complex inside, just like our human

body” Matz

Page 4: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html

Page 5: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Introduction to Ruby

http://www.rubyist.net/~slagell/ruby/index.html

Page 6: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Grammar

Nick Sieger http://blog.nicksieger.com/articles/2006/10/27/visualization-of-rubys-grammar/

Page 7: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Introduction to Ruby

• Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean?

• object oriented programming:– everything is an object

classes, methods, multiple inheritance, etc.– "mixin" functionality by module– iterators and closures

(http://www.artima.com/intv/closures.html)

http://www.rubyist.net/~slagell/ruby/index.html

Page 8: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Introduction to Ruby

• Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean?

• also:–multiple precision numbers– convenient exception processing–dynamic loading– threading support.

http://www.rubyist.net/~slagell/ruby/index.html

Page 9: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Ruby, Perl and Python

• Design goals– Expressive like perl but better Object-Orientation– Like python but implementing true Object-Orientation–No primitive types, everything is an object/class– Fully scriptable

Page 10: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

RubyGems

• A RubyGem is a software package, commonly called a “gem”.

• Gems contain a packaged Ruby application or library.

• The RubyGems software itself allows you to easily download, install, and manipulate gems on your system

http://guides.rubygems.org/

Page 11: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Ask an experienced ruby programmer about ruby …

• “What is most amazing about Ruby is a community, they are sharing really a lot. I guess it exploded with github (written in Ruby), at the beginning, github had its own rubygems hosting. Later, other project appear with its own hosting and github dropped its rubygems hosting service and suggested to switch to new one. Now the tool is a official one (rubygems.org).”• “Also, the same thing is with documentation. Every

major project hosts its documentation but there are many aggregators that are hosting ruby stdlib and core documentation also with documentation of many gems - http://ruby-doc.org/ or http://rubydoc.info”

Page 12: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Git Hub

• GitHub is the best place to share code with friends, co-workers, classmates, and complete strangers. Over two million people use GitHub to build amazing things together.

http:/github.com/

Page 13: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Successful story about ruby• cloud application platform – deploy and scale powerful apps

• Agile deployment for Ruby and other languages.– Get up and running in minutes, and deploy instantly with git. Focus 100%

on your code, and never think about servers, instances, or VMs again.”• Run and scale any type of app.– “Run any web or background process with any web framework or worker

type. Scale distributed processes effortlessly with a single command. Easily scale to millions of users.”

• Total visibility across your entire app.– View consolidated, real-time logging and status from every component of

your app and from Heroku itself as it deploys your app, manages your processes, and routes traffic

http://www.heroku.com

Page 14: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Successful story about ruby

• RVM is the Ruby Version Manager.– It allows to install and manage several different versions and

implementations of Ruby on one computer,– including the ability to manage different sets of RubyGems

one each.

http://rvm.io

Page 15: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Successful story about ruby

• Bundler ensures that your project will use the exact gems – Define rubygem source– Specify gems and versions using operators (“>=”,

“~>”)

http://bundler.io

Page 16: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Successful story about ruby

• Rack– Inspired by WSGI (Web Server Gateway Interface of

Python)– Provides a minimal interface for http servers

http://rack.github.io

Page 17: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Ruby on Rails (RoR)

• Rails is an open source Ruby framework for developing database-backed web applications.

• All layers in Rails are built to work together so you Don’t Repeat Yourself and can use a single language from top to bottom.

• Everything in Rails is written in Ruby– Except for configuration files - YAML

18

shows how to create a simple blog webapp in 15 mins. ( of course with experts hands )http://media.rubyonrails.org/video/rails_take2_with_sound.mov

Page 18: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

How about the issue

• “The worse thing about Ruby itself is a fact that it allow programmer to overload everything. It means that if you do a monkey patching - if you change one thing like class, module in runtime - you change them in a whole environment, e.g., if you include a library which changes http module from Ruby core, it changes it in a whole environment.”• Also, the syntax is very tricky, e.g.:foo.bar x is euiqvalent to foo.bar(x)• but:foo.bar { ... } # passes a block to functionfoo.bar({ ... }) # passes a hash table to function 19

Page 19: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Ruby Basics

• Normal method for scripting using #!/usr/bin/ruby

• irb is an interactive ruby interpreter– You can interpret single lines of code–Good for simple checking and debugging

• You can document Ruby code using the RDoc system– The documentation is inside the source file– It can be extracted using ri– To find the documentation for a class type

ri classname at the command prompt

Page 20: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Simple Example

#!/usr/bin/ruby#helloworld example in Rubyputs “Hello world”

$ chmod a+x helloWorld.rb$ helloWorld.rbHello world$

Page 21: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

ES: Ruby

• Today:1.Ruby introduction2.Basic Ruby: types, variables, statements, methods3.Regular expression4.File and I/O5.Modules6.Packages7.Object Oriented ruby8.Documentation

Page 22: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Numbers

Simple numbers:–binary, start with 0b: 0b1100, -0b10001, 0b11111111 . . .–decimal: 12, -17, 255 . . .–octal, start with 0: 015, -023, 0777 . . .–hexadecimal, start with 0x: 0xc, -0x11, 0xff, . . .–floating point numbers:

“one and a quarter ": 1.25– scientific notation:

“7.25 times 10 to the 45th power ": 7.25e45.

But also matrices and complex numbers using separate modules

Page 23: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Strings (1)• To create string literals, enclose them in single, or double

quotes.

• Examples:'Hello Class of 2012'"Ruby is shiny”

• The same type of quote used to start the string must be used to terminate it.

• You can have your own delimiters using %q or %Q%q!"I said 'nuts'", I said! # %q - applies the simple quote rules%Q(It's like a " string,\n \\n is a newline) # %Q applies the double quote rules

If you use () {} [] as delimiter you can use these delimiters as a text as long as they are in pairs

Page 24: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Strings (2)

• Escape sequences for single quoted (') strings: only \\ and \’

• For double quoted (‘”’) strings:\a, \b, \e, \f, \n, \r, \s, \t,

• You can embed ruby code into a double quoted string using #{. . . }:

"Seconds/day: #{24*60*60}” Seconds/day: 86400

Page 25: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Strings (3)

• Intermittent single and double quoted strings are concatenated to one object:

"'Well'" ', he said, ' '"How are you?"’

'Well', he said, "How Are You?”

• You can construct a multiline string using a “here document”:

string = <<END_OF_STRINGThe Body of the string is the input

lines up to one ending with the same text that followed the '<<'END_OF_STRING

Page 26: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Variables and Constants

• Ruby variables and constants hold references to objects.

– The object decides the type, not the variable–Reassignment can change the type of the variable

• Naming is as follows:Constants start with a [A-Z], the convention is to

write all caps with underscoreslocal variables start with a [a-z\_]global variables start with a `$'instance variables start with a `@’class variables start with `@@’

Page 27: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Predefined variables

• Most predefined variables come from perl

• There are predefined variables for:Input/Output ($_, $., …)Pattern Matching ($=, $1 to $9, …)Execution Environment (Ruby specific) ($0, $”, …)Exception information ($!, $@)Standard objects (true, false, ARGV, …)global Constants (STDIN, STDOUT, …)

http://www.softlab.ntua.gr/facilities/documentation/unix/ruby-man-1.4/variable.html#equal

Page 28: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

String variables

• String variables are indexed like lists, starting at 0• You can use them using the index operator `[i]'

a = "Hello World"b = a[4] # b = o

• Substrings can be used by pair numbers: `[start,count]'

c = a[0,6] # c = "Hello "d = a[7,4] # d = "orld"e = a[3,5] # e = "lo Wo”

• Ranges can also be used to specify indices.

Page 29: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Ranges

• Construct ranges of numbers or characters• Use double dot notation for inclusive range creation:

1..5.to_a [1, 2, 3, 4, 5]• Use triple dot notation for exclusive range creation:

1...5.to_a [1, 2, 3, 4]

Example for string variables:a = "Hello World"c = a[0..5] # c = "Hello "d = a[7..10] # d = "orld"e = a[3...9] # e = ?

Page 30: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Arrays

• Arrays are arbitrary lists of objects• Create an Array using [ ]:

names = [“Fred”,2,"Flintstone”]• They too are indexed:

a = names[1] # a is now 2names[0] = “Wilma” # names is

changed

• Using a range:names[1..2] [ 2, "Flintstone" ]

Page 31: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Hashes (1)

• A hash contains objects indexed by keys.• Any object can be used as a key or value, but . . .• Create a hash by enclosing `key => value’

combinations in curly braces (`{. . . }'):

a = {"username" => "xenos", "home" => "/home/xenos”,

"uid" => 500}

Page 32: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Hashes (2)

• Access any value using it's key:u = a["username"] # Returns "xenos"d = a["home"] # Returns "/home/xenos”

• To insert or modify objects, you assign a value to a key-indexed name.

a["username"] = "trixie"a["home"] = "/home/trixie"a["shell"] = "/usr/bin/tcsh"

Page 33: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Hashes (3)

• Hash membership is tested with several methods: has_key?, has_value?, keys, values

a.has_key? "username” # return Truea.has_value? "trixie” # return falsea.keys # ["username", "uid", "shell", "home"]a.values # ["xenos", 500, “/usr/bin/tcsh”,

"/home/xenos”]

Page 34: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Expressions

• Single terms are:– Literals (numbers, strings, arrays, hashes, ranges, symbols, RE's)– Shell commands, using backquotes: `. . . `

files = `ls *`–Variable or constant references• Expression blocks are denoted by begin/do . . . end• The usual operators:

+, -, *, /, %, **, !, …• Most operators are implemented as methods (may be overridden)

Page 35: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Assignment

• Using parallel assignment in place of using temporary variables:

a = 1b = 2temp = aa = bb = temp

Using parallel assignment:a, b = b, a

Page 36: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

ES: Ruby

• Today:1.Ruby introduction2.Basic Ruby: types, variables, statements, Functions3.Regular expression4.File and I/O5.Modules6.Packages7.Object Oriented ruby8.Documentation

Page 37: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Comparison Operators

== Test for equal value=== Comparison operator<=> General comparison operator (returns -1, 0, 1)<, <=, >, >= Normal comparison operators=~ Regular expression match

eql? Checks for type and value equalityequal? Checks for Object ID equality

Page 38: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Flow control

• Code blocks are denoted by { . . . } or do . . . end blocks• Code blocks can start with an argument list between

vertical bars: |…|

#!/usr/bin/rubypresidents = ["Ford", "Carter", "Reagan", "Bush1", "Clinton”]

• presidents.each {|prez| puts prez}

• Flow control can be exerted using looping or conditional statements.

Page 39: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Looping Statements (1)• The standard constructs are present:

while conditionbody

end• Using a begin . . . end block the syntax can be reversed:

beginbody

end while condition

until conditionbody

end

beginbody

end until condition

Page 40: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Looping Statements (2)

• Iterating over the members of a sequence containing any type of object.

for i in [1,2,"three", 4, 5,'eleven', 7 ]

print i," "end

• You can also use a range:for i in 1..10

print i," "end

Page 41: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Looping Statements (3)

• Most standard object types also provide iterator methods Examples for numbers:

3.times doprint "Hi! "

end

0.upto(93) doprint "Ha! "

end• For arrays/files/etcetera there are:obj.each, obj.foreach, . . .

Page 42: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Conditional statements (1)

• if and unless statements:if test [ : | then]

bodyelsif test [ : | then ]

bodyelse

bodyend• You can also use them on expressions as modifiers:expression if testexpression unless test

unless test [ : | then ]body

elsebody

end

Page 43: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Conditional Statements (2)

• case statement compares each when clause to a target and executes the first match

case targetwhen comparison [: | then]

bodywhen comparison [: | then]

body. . .[else

body ]end

http://ilikestuffblog.com/2008/04/15/how-to-write-case-switch-statements-in-ruby/

Page 44: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

ES: Ruby

• Today:1.Ruby introduction2.Basic Ruby: types, variables, statements, Methods3.Regular expression4.File and I/O5.Modules6.Packages7.Object Oriented ruby8.Documentation

Page 45: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Methods (1)

• A method can have arguments, they are passed to the block as an array

• A method will return the result of the last executed expression in the block as the return value

• The return expression will exit the method immediately giving its argument as a return value

Page 46: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Methods (2)

• A simple method definition is as follows:

def sayhi(name)print "Hi", name

End

• A definition using pre-initialized arguments:

def options(a=99, b=a+1)[ a, b ]

end

options [99, 100]options 1 [1, 2]options 2, 4 [2, 4]

Page 47: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Methods (3)• super method is a special method for objects– It executes the function of the same name in the parent object– to ensure creation or initialization of parent objects

• super with no arguments – Ruby sends a message to the parent of the current object,– to invoke a method of the same name as the method invoking

super.– It automatically forwards the arguments that were passed to the

method from which it's called.• super() with an empty argument list– it sends no arguments to the higher-up method, even if arguments

were passed to the current method.• super(a, b, c) with specific arguments– it sends exactly those arguments.

Page 48: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

ES: Ruby

• Today:1.Ruby introduction2.Basic Ruby: types, variables, statements, methods3.Regular expression4.File and I/O5.Modules6.Packages7.Object Oriented ruby8.Documentation

Page 49: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Regular Expressions

• Regular expressions are an object of type Regexp• They can be created using:

/ pattern / [options]%r{ pattern } [options]Regexp.new(' pattern ' [ , options] )

• Most standard options and patterns are available• For more information see the documentation

Page 50: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Regular Expressions

• r1 = Regexp.new('^a-z+:\\s+\w+') #=> /^a-z+:\s+\w+/

a = "HELLO” case a when /^[a-z]*$/; print "Lower case\n” when /^[A-Z]*$/; print "Upper case\n” else; print "Mixed case\n” end

Page 51: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Regular Expressions

#!/usr/bin/ruby

phone = "2004-959-559 #This is Phone Number"

# Delete Ruby-style commentsphone = phone.sub!(/#.*$/, "") puts "Phone Num : #{phone}"

# Remove anything other than digitsphone = phone.gsub!(/\D/, "") puts "Phone Num : #{phone}"

Page 52: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

ES: Ruby

• Today:1.Ruby introduction2.Basic Ruby: types, variables, statements, methods3.Regular expression4.File and I/O5.Modules6.Packages7.Object Oriented ruby8.Documentation

Page 53: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Opening and Closing Files

• File.new Method

aFile = File.new("filename", "mode")# ... process the fileaFile.close

• File.open Method

File.open("filename", "mode") do |aFile| # ... process the fileend

Page 54: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Reading and Writing Files

• aFile.gets reads a line from the file object aFile.

• I/O objects provides additional set of access methods– sysread: read the contents of a file.– syswrite : write the contents into a file.– each_byte: Characters are passed one by one• The method each_byte is always associated with a block.

Page 55: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

sysread

#!/usr/bin/ruby

aFile = File.new("/var/www/tutorialspoint/ruby/test", "r")if aFile content = aFile.sysread(20) puts contentelse puts "Unable to open file!"end

Page 56: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

syswrite

#!/usr/bin/ruby

aFile = File.new("/var/www/tutorialspoint/ruby/test", "r+")if aFile aFile.syswrite("ABCDEF")else puts "Unable to open file!"end

Page 57: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

each_byte

#!/usr/bin/ruby

aFile = File.new("/var/www/tutorialspoint/ruby/test", "r")if aFile aFile.syswrite("ABCDEF") aFile.each_byte {|ch| putc ch; putc?. }else puts "Unable to open file!"end

Page 58: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

• The class File is a subclass of the class IO. –IO.readlines–IO.foreach

• Renaming and Deleting Files–File.rename( "test1.txt", "test2.txt" )–File.delete("text2.txt")

Page 59: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

File Inquiries

• File.open("file.rb") if File::exists?( "file.rb" )• File.file?( "text.txt" ) • File::directory?( "/usr/local/bin" )• File.readable?( "test.txt" ) File.writable?( "test.txt” )• File.executable?( "test.txt" )• File.zero?( "test.txt" )• File.size?( "text.txt" )

Page 60: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

ES: Ruby

• Today:1.Ruby introduction2.Basic Ruby: types, variables, statements, Functions3.Regular expression4.File and I/O5.Modules6.Packages7.Object Oriented ruby8.Documentation

Page 61: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Modules (1)

• Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits.–Modules provide a namespace and prevent name clashes.–Modules implement the mixin facility.

• A Ruby Module is basically a class that cannot be instantiated• Multiple modules may be created in a single source file• Use the definitions in a module in the same way you would an

(instantiated) object• A redefinition of a module results in overloading that module

Page 62: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Modules (2)

• A module definition:CONST = "outer"module A

CONST = 1def A.method

CONST + 1end

end

• Questions:CONST -> "outer"A::CONST -> 1A.method -> 2

Page 63: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Modules (3)

• A module definition with scope inheritance:CONST = "outer"module B

def B.method CONST + "scope"

endend

• Question:B.method -> "outerscope”

Page 64: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Modules (4)

• Modules can be included in the definition of another module or class use:

include <module-name>• The including module will have access to all

constants, variables, methods etcetera from the included module• A class may also include a module– The module will be treated as a superclass for the class– The module can also contain an initialize method

Page 65: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Modules (5)

module SillyModuledef hello

"Hello."end

end

Questions.hello -> ”Hello”

class SillyClassinclude SillyModule

End

s = SillyClass.new

Page 66: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Including Source files

• Include Ruby source files into a program using load or require

Load loads the referenced file each time it is called Useful for (re)loading source code generated at run- timerequire loads the referenced file only once. require is a statement, it can be use anywhere statements are allowed

For instance from within an if statement.

• Local variables in a loaded file are not propagated to the scope of the loading file

Page 67: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

ES: Ruby

• Today:1.Ruby introduction2.Basic Ruby: types, variables, statements, methods3.Regular expression4.File and I/O5.Modules6.Packages7.Object Oriented ruby8.Documentation

Page 68: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Classes (1)

• A ruby class is an extension of the class Class• Class names start with a [A-Z]• Classes create a new namespace• Classes can be nested, but they will not be made global,

so instantiation requires the fully qualified classname• A simple example definition:

class MyClassCONST = 12345def f

'hello world'end

end

Page 69: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Classes (2)• Create an instance object from a class as follows:

obj = MyClass.new

• The class Class defines a method new which is responsible for the creation of an object of the class

– The new method must call the super method to allow the parent class to be allocated, otherwise no objects of that class can be created.

• The class Class also defines the method initialize, which will be invoked in a newly created object, it will receive the arguments passed to new.

– The initialize method must also call super if the parent object is to be properly initialized

Page 70: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Classes (3)

• To use a method from an object use a dot notation:obj.f• To retrieve a constant from an object use the double

colon notation: obj::CONST

• Examples:obj.f # hello worldobj::CONST # 12345

Page 71: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Classes (4)

Class variables• class variables are variables shared between all

objects of a class

class Song@@plays = 0def play

@@plays += 1"This song: Total #@@plays plays."

endend

Page 72: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Classes (5)

Class methods - object methods vs. class methods

- a class may need to provide methods that work without being tied to any particular object. For example MyClass.new.

• Example

class Exampledef instMeth # instance methodenddef Example.classMeth # class methodend

end

Page 73: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Documentation

• Ruby vs Python -> http://vimeo.com/9471538• Matz about Ruby 2.0 -> http://vimeo.com/61043050• BOOKS!, they are in the back of the classroom. . .• Use the web, there are good websites on ruby• Check http://www.ruby-lang.org/ for help.• http://www.ruby-doc.org/docs/ruby-doc-bundle/index.ht

ml • “Programming Ruby", can be found online via above link

Page 74: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around

1.write a function fact to compute factorials.– The mathematical definition of n factorial is:

n! = 1 (when n==0) = n * (n-1)! (otherwise) 2.write a simple ruby prog with case statement where given a

model of a car it prints the brand

3.write a simple ruby prog with arrays, print the element of the array, remove elements, prepend elements – Hint: Ruby arrays have methods shift, unshift, push, and pop)

4.write a simple ruby with control statement if. When given democrats it prints the names of democrats presidents in US since 1976, same for republicans

Page 75: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around

1.write a class Decade and a module Week to print the number of weeks in a month, a year, and the number of days in a decade (include the Week module in the Class Decade)

2.write a class with runtime Exception handling. If the age of a given patient is bellow a certain age, it generate an exception.–Hints: use raise to generate the exp, and rescue to catch it

Page 76: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around

1.write a function fact to compute factorials.– The mathematical definition of n factorial is:

n! = 1 (when n==0) = n * (n-1)! (otherwise)

# Program to find the factorial of a number# Save this as fact.rbdef fact(n) if n == 0 1 else n * fact(n-1) endendputs fact(ARGV[0].to_i)

Page 77: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around1. write a simple ruby prog with case statement where given a model of a car it prints

the brandcar = "Patriot”manufacturer = case car when "Focus": "Ford" when "Navigator" then "Lincoln" when "Camry" then "Toyota" when "Civic" then "Honda" when "Patriot": "Jeep" when "Jetta" ; "VW" when "Ceyene” "Porsche” when "520i" then "BMW” else "Unknown"endputs "The " + car + " is made by " + manufacturer

Page 78: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around1. write a simple ruby prog with arrays, print the element of the array remove

elements, prepend elements – Hint: Ruby arrays have methods shift, unshift, push, and pop)

#!/usr/bin/rubypresidents = ["Ford", "Carter", "Reagan", "Bush1", "Clinton", "Bush2"]presidents.each { |i| print i, "\n"}

#Remove 3 elements from the array#!/usr/bin/rubypresidents = ["Ford", "Carter", "Reagan", "Bush1", "Clinton", "Bush2"]presidents.poppresidents.poppresidents.poppresidents.each { |i| print i, "\n"}

Page 79: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around1. write a simple ruby prog with arrays, print the element of the array, remove

elements, and prepend elements – Hint: Ruby arrays have methods shift, unshift, push, and pop)

#!/usr/bin/rubypresidents = ["Ford", "Carter", "Reagan", "Bush1", "Clinton", "Bush2"]presidents.each { |i| print i, "\n"}

#Prepend 3 elements to the array#!/usr/bin/rubypresidents = ["Ford", "Carter", "Reagan", "Bush1", "Clinton", "Bush2”]presidents.unshift("Nixon")presidents.unshift("Johnson")presidents.unshift("Kennedy")presidents.each { |i| print i, "\n"}

Page 80: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around1. write a simple ruby with control statement if. When given democrats it prints the names of

democrats presidents in US since 1976, same for republicans

#!/usr/bin/rubydemocrats = ["Carter", "Clinton”] republicans = ["Ford", "Reagan", "Bush1", "Bush2”] party = ARGV[0]if party == nil print "Argument must be \"democrats\" or \"republicans\"\n"elsif party == "democrats" democrats.each { |i| print i, " "} print "\n"elsif party == "republicans" republicans.each { |i| print i, " "} print "\n"else print "All presidents since 1976 were either Democrats or Republicans\n"end

Page 81: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around

1.write a class Decade and a module Week to print the number of weeks in a month, a year, and the number of days in a decade (include the Week module in the Class Decade)

#!/usr/bin/rubyrequire "Week”class Decade include Week no_of_yrs=10 def no_of_months puts Week::FIRST_DAY number=10*12 puts number endend

!/usr/bin/rubymodule Week FIRST_DAY = "Sunday" def Week.weeks_in_month puts “four weeks in a month" end def Week.weeks_in_year puts “52 weeks in a year" endend

Page 82: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around

1.write a class Decade and a module Week to print the number of weeks in a month, a year, and the number of days in a decade (include the Week module in the Class Decade)

#!/usr/bin/rubyrequire "Week”class Decadeinclude Weekno_of_yrs=10def no_of_months puts Week::FIRST_DAY number=10*12 puts numberendend

d1=Decade.newputs Week::FIRST_DAYWeek.weeks_in_monthWeek.weeks_in_yeard1.no_of_months

Page 83: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around1.write a class with runtime Exception handling. If the age of a given patient

is bellow a certain age, it generate an exception.•.Hints: use raise to generate the exp, and rescue to catch it

class MedicareEligibilityException < RuntimeError def initialize(name, age) @name = name @age = age end def getName return @name end def getAge return @age endend

… next page …

Page 84: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Arounddef writeToDatabase(name, age) # This is a stub routine print "Diagnostic: ”,name, ”,age ", age, " is signed up.\n"enddef signHimUp(name, age) if age >= 65 : writeToDatabase(name, age) else myException = MedicareEligibilityException.new(name, age) raise myException , "Must be 65 or older for Medicare", callerEndend … next page …

Page 85: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around# Main routinebegin signHimUp("Oliver Oldster", 78) signHimUp("Billy Boywonder", 18) signHimUp("Cindy Centurinarian", 100) signHimUp("Bob Baby", 2)rescue MedicareEligibilityException => elg print elg.getName, " is ", elg.getAge, ", which is too young.\n" print "You must obtain an exception from your supervisor. ", elg, "\n”endprint "This happens after signHimUp was called.\n"

Page 86: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around1.write a simple prog with two classes Mammal and cat the cat Class extends

Mammal.•

# class Mammal def breathe puts "inhale and exhale" endend

class Cat<Mammal def speak puts "Meow" endend

tama = Cat.newtama.breathetama.speak

Page 87: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around• write a prog for reduced far for the train (3 Classes Traveler, Student,

Honest, both Student and Honest inheritance

class Traveler def identify puts "I'm a Traveler." end def train_toll(age) if age < 12 puts "Reduced fare."; else puts "Normal fare."; end endend

Page 88: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Play Around

class Student<Traveler def identify puts "I'm a student." endendclass Honest<Traveler def train_toll(age) super(age) # pass the argument we were given end endTraveler.new.identifyStudent1.new.identifyHonest.new.train_toll(25)

Page 89: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Assignment

We will be creating an Alumni database system.1. Create a class 'alumnus' to store a single person or alumnus in. Create a method for separately adding friends (by reference to an existing alumnus object!)

2. Test the class by creating a group of alumni who are friends.

3. Not all alumni have to be direct friends, you can also have acquaintances. They are friends of your friends that are not your direct friend. So: a distance of 1 is your friend, a distance of 2 is an acquaintance and more than 2 is unknown.

Page 90: Ruby - OS3 to Ruby • Ruby is "an interpreted scripting language for quick and easy object-oriented programming" -- what does this mean? • object oriented programming: –everything

Assignment

4. Create a class that prints information about a single alumnus4.1 Create a method for printing all friends of the alumnus by name4.2 Create a method for printing all acquaintances of the alumnus by name4.3 Create a method that prints ALL connected alumni at any distance for the given alumnus. For each connection print the distance number, the type of relation and the alumni through which they are connected So:2 : acquaintance : eelco -> jarno -> karst implies that eelco knows karst through jarno, meaning jarno is a friend and karst is an acquaintance. Note that there can be multiple ways that eelco knows karst, always choose the shortest route, and never show a connection twice