程序代写代做代考 flex scheme RUBY

RUBY
#3 Methods and Classes
Dr. Jozo Dujmović
© Jozo Dujmović Ruby #3 1

Ruby is not a small language
• Methods belong to libraries
• Number of various standard libraries that
come with Ruby 1.8 = 98
• Number of methods that come with Ruby
is currently 9000++
• These methods are documented in RDoc,
available at http://www.ruby-doc.org
• ri is a local command line viewer of RDoc
© Jozo Dujmović Ruby #3 2

© Jozo Dujmović Ruby #3 3

© Jozo Dujmović Ruby #3 4

Using ri -c to find all classes
© Jozo Dujmović Ruby #3 5

Using ri ClassName
© Jozo Dujmović Ruby #3 6

Using ri to find specific method
© Jozo Dujmović Ruby #3 7

© Jozo Dujmović Ruby #3 8

© Jozo Dujmović Ruby #3 9

Methods
• Method is a named collection of statements that can be called repeatedly
• Method can be defined (using keyword def) and undefined (using keyword undef)
• Methods return the last expression that is evaluated
• Methods can use the return statement to return a value
• Methods are sometimes used only for side
effects
© Jozo Dujmović Ruby #3 10

© Jozo Dujmović Ruby #3 11

Methods – syntax
• Methodisinsertedinsidedef–end
• Methodnamenormallystartswithalowercase letter. The trailing letter can be ‘?’ (used for recognizers), ‘!’ (dangerous), or ‘=‘ (used for class instance setters)
• Syntax:
def [ [( ] ,…, [ )] ]
end
• Simpleargumentsarelocalvariablesofthe method (must be lowercase); their scope is within the method
© Jozo Dujmović Ruby #3 12

Convention about parentheses
• Parentheses are optional. If there are local arguments it is suitable (because of notation in math and other languages) to use parentheses
• If there are no arguments the empty parentheses ( ) can be omitted
© Jozo Dujmović Ruby #3 13

© Jozo Dujmović Ruby #3 14

Default values of method arguments
• Ruby permits the use of default values of method arguments
• Default values are used if the user does not provide the values of arguments
• The list of arguments can have variable length
© Jozo Dujmović Ruby #3 15

© Jozo Dujmović Ruby #3 16

Return values
• Everymethodreturnsavalue
• Thereturnedvaluemayormaynotbeused
• Thereturnedvalueofthemethodisthevalueof the last executed statement
• There might be one or more returned values
• Multiplereturnedvaluescanbereturnedby
return first, second, third
• Multiple returned values are returned in an array: [first, second, third]
© Jozo Dujmović Ruby #3 17

© Jozo Dujmović Ruby #3 18

Using side effects
© Jozo Dujmović Ruby #3 19

Ruby methods can modify (in situ) and return arrays
© Jozo Dujmović
Ruby #3 20

Expanding arrays in method calls
• List of scalar arguments can be replaced by arrays or their parts
• Such arguments must be prefixed by an asterisk (“splat operator”)
• The number of arguments must be correct (array cannot be larger than the original number of arguments)
© Jozo Dujmović Ruby #3 21

Expanding arrays
© Jozo Dujmović Ruby #3 22

Method with an arbitrary number of arguments: multiple arguments are bundled into an array. A method can return an empty array
© Jozo Dujmović
Ruby #3 23

“Splat operator” ( * )
It can be use to split array and distribute it to specific arguments of the method
© Jozo Dujmović Ruby #3 24

Class Array methods
• Definition: array is an ordered, integer-indexed collection
of any object
• Array indexing starts at 0
• Ruby uses circular indexing a[-1] = last element of array, a[-2] = element before a[-1]
• Array elements can have different data types
• Example of an array: [“a”, ”b, ”c”, 1, 2, 3]
• Array = array class name
• Array.new = class method that creates a new array object
• a = Array.new is equivalent to a = [ ]
• a[int] is object or nil
• a[start, length] = subarray a[start … start+length-s]
• a[p .. q] = subarray of given range a[p .. q]
© Jozo Dujmović Ruby #3 25

MAKE ARRAY
SORT TEST
SHOW ARRAY
© Jozo Dujmović
Ruby #3 26

SHOW ARRAY METHOD
Note:
show(a) works similarly as the kernel method p
© Jozo Dujmović
Ruby #3 27

Basic array instance methods
• Intersection
• Union
• Repetition
• Concatenation
• Difference
• • • • • • • • • •
Include Delete Clear Reverse First Each
Sort transpose to_a
• Append
• Compare a <=> b returns -1, 0, 1 for ab
• Equality of arrays ==
© Jozo Dujmović Ruby #3
to_s
28

© Jozo Dujmović Ruby #3 29

Kernel method p for printing
© Jozo Dujmović Ruby #3 30

© Jozo Dujmović Ruby #3 31

Tail recursion in Ruby
© Jozo Dujmović Ruby #3 32

Classes
• Classisacontainerforvariablesandmethods
(“properties”)
• Classcaninheritpropertiesfromasingleparent
class (no multiple inheritance)
• Thebase(root)classinRubyisObject
• Classesarealwaysopen(itispossibletoaddto any class including the build-in classes)
Object
Numeric
Complex Rational
© Jozo Dujmović
Ruby #3
33
Integer
Fixnum Bignum
Float

• Basic syntax:
Classes – Syntax
class …………………… end
• Classname must be CONSTANT (i.e. it must beging with a capital letter)
• @var = instance variable (private variable reachable using an accessor method)
• @@var = class variable (shared among all instances of a class)
© Jozo Dujmović Ruby #3 34

The instance variables are accessible to all class member functions (they act as global
variables for the member functions)
© Jozo Dujmović Ruby #3 35
The instance variables @length, @width, @height are private attributes (descriptors) of each instance of the Box object.
The initialize method is the constructor-initializer of an instance. Its role is to reserve memory space for instance variables @length, @width, @height, and to instantiate their values using the x,y,z arguments. Initialize is activated by Box.new(…).
Box.new(1,2,3) is a constant anonymous object (a nameless set of initialized @length, @width, @height instance variables).

Expanding existing classes
• All existing classes come with a number of methods. E.g. Array includes methods:
&, *, +, -, <<, <=>, ==, [ ], [ ]=, abbrev, assoc, at, clear, collect, collect!, compact, compact!, concat, dclone, delete, delete_at, delete_if, each, each_index, empty?, eql?, fetch, fill, first, flatten, flatten!, frozen?, hash, include?, index, indexes, indices, initialize_copy, insert, inspect, join, last, length, map, map!, nitems, pack, pop, pretty_print, pretty_print_cycle, push, quote, rassoc, reject, reject!, replace, reverse, reverse!, reverse_each, rindex, select, shift, size, slice, slice!, sort, sort!, to_a, to_ary, to_s, to_yaml, transpose, uniq, uniq!, unshift, values_at, yaml_initialize, zip, |
• Users can expand the collection of methods of existing classes by adding new methods
• Example: add special initialization and display methods for arrays
© Jozo Dujmović Ruby #3 36

© Jozo Dujmović
Ruby #3 37
When expanding an existing system class (Array) the initialization of the object is out of reach of user.
However, the current object (array) can be manipulated using the pseudovariable self .
By defining new methods inside existing classes, we can expand and improve existing method libraries and add new functionality.

Incremental build of the class Box
© Jozo Dujmović Ruby #3 38

The concept of pseudovariable
• Propertiesofpseudovariables:
They look as all other variables
They act as constants (cannot be assigned a value)
• Ruby pseudovariables:
self = current object, invoked by a method
true = logical true; an instance of TrueClass
false = logical false; an instance of FalseClass
nil = empty/uninitialized/invalid; an instance of NillClass
__FILE__ = name of current source file
__LINE__ = number of current line in the current source file
© Jozo Dujmović Ruby #3 39

© Jozo Dujmović Ruby #3 40

Getters and setters
• Getter = a method for reading instance variables (object attributes) from programs that are not class members
• Setter = a method for writing instance variables (object attributes) from programs that are not class members
• Ruby convention: setter name usually terminates with “=“
© Jozo Dujmović Ruby #3 41

Getters and setters for the class Box
© Jozo Dujmović Ruby #3 42

Classes inherit a basic set of instance methods from the root class Object. In the case of the class Box the only method that is not inherited is “volume”
© Jozo Dujmović Ruby #3 43

Accessors for instance variables
• Let ivar be an instance variable of an object obj. Ruby provides the following four accessors (getters and setters):
=> obj.ivar [obj.ivar=] => obj.ivar
=> obj.ivar=
attr :ivar [, true]
attr_reader :ivar
attr_writer :ivar
attr_accessor :ivar => obj.ivar , obj.ivar=
• attr_accessor is a general solution
© Jozo Dujmović Ruby #3 44

© Jozo Dujmović Ruby #3 45

In a special case the initializer can be used without arguments
© Jozo Dujmović Ruby #3 46

Class variables
• Class variables are prefixed by @@
• All instances share the same @@classvar
• Class variables are suitable as counters and accumulator
• If used as accumulators or counters the class variables must be initialized before their use
© Jozo Dujmović Ruby #3 47

© Jozo Dujmović Ruby #3 48

Class (static) methods
• Class method belongs to a class
• Classmethodisnotassociatedwithaninstance of a class
• Class method is defined prefixed with self (which needs never to be changed) or the name of the class to which it belongs (which might be changed)
• Class method is invoked prefixed with the name of the class to which it belongs, like Math.sqrt(x)
© Jozo Dujmović Ruby #3 49

© Jozo Dujmović Ruby #3 50

• Syntax:
class Old class = superclass/parent class New class = subclass/child class
…..
Inheritance
• Inheritance is a method to create a class that is a refinement or specialization of another class
end
class < …..
end
© Jozo Dujmović Ruby #3 51

© Jozo Dujmović Ruby #3 52

Access Control
• Public methods: can be called by anyone (this is default, except for initialize, which is always private)
• Protected methods: access is restricted to family (accessed by the class and its subclasses/children)
• Private methods: cannot be called with receiver other than self
© Jozo Dujmović Ruby #3 53

Equivalent notation
© Jozo Dujmović Ruby #3 54

Elements of input/output
• Input/output comes from several sources:
– Command line argument
– Keyboard
• Interactive mode
• Interpretative mode
– Files
• Keyboard input and command line input are processed in the command line environment
© Jozo Dujmović Ruby #3 55

Using command line arguments • Program file CommndLineArguments.rb:
• Execution in the command prompt mode:
>ruby CommandLineArguments.rb 1 4 5
Mean value of (1.0, 4.0, 5.0) = 3.33333333333333
© Jozo Dujmović Ruby #3 56

© Jozo Dujmović
Ruby #3
57
>ruby AriTest.rb
Enter your name: Ruby Hello Ruby
Enter the first number : 1.1111 Enter the second number: 2.2222
Select 1, 2, 3, 4 for +, -, *, / : 4 The result = 0.5
You selected division
Select 1, 2, 3, 4 for +, -, *, / : 5 The result = Error
You selected a wrong operator
Select 1, 2, 3, 4 for +, -, *, / : 1 The result = 3.3333
You selected addition

Parentheses can be omitted. These two versions work in the same way
© Jozo Dujmović Ruby #3 58

• Dir=classformanipulatingdirectories
• File=classtomanipulatefiles – Create
– Open
– Rename – Delete
Files
Dir.chdir(“/Users/bill/ruby”)
home = Dir.pwd # Users/peter/ruby Dir.mkdir(“/Users/bill/scheme”) Dir.rmdir(“/Users/bill/pascal”)
© Jozo Dujmović Ruby #3 59

• Create and open file for writing file = File.new(“data.txt”, “w”)
• Modes:
“r” = read only, start from beginning
Create file
“r+” = read-write, start from beginning
“w” = write only (create new or overwrite an existing file)
“w+” = write-read (create new or overwrite existing file)
“a” = append (write only) or create new file, start at EOF
“a+” = append (read-write) or create new file, start at EOF
“b” = binary file mode (DOS/Windows only)
© Jozo Dujmović Ruby #3 60

Open/close file
file = File.open(“data.txt”)
file.each{ |line| print “#{file.lineno}“, line } file.close
File.open(“data.txt”) if File::exists?(“data.txt”)
© Jozo Dujmović Ruby #3 61

Rename, Delete, Test
file = File.new(“data.txt”, “w”) File.rename(“data.txt”, “junk.txt”) File.delete(“junk.txt”)
file.closed? # returns true/false file.size # returns size in bytes
© Jozo Dujmović Ruby #3 62

Basic numeric methods (Math)
• Recognizers
• • •
Trigonometry Hyperbolic functions
• Rounding
• Absolute value
Fraction/exponent decomposition
• Sign
• • •
Error function BigDecimal arithmetic
• Constants
• Not a number
Complex numbers and functions
• Infinity
• Roots
• • •
Rational numbers and rational arithmetic oper.
• Logarithms/exponentials
• Cartesian/polar conversion
Random numbers (seed and computation)
• Dates and time measure © Jozo Dujmović
Ruby #3
Vectors and matrices
63

© Jozo Dujmović Ruby #3 64

Accurate time measurement
© Jozo Dujmović Ruby #3 65

Matrix operations
© Jozo Dujmović Ruby #3 66

Solving a quadratic equation with complex coefficients
© Jozo Dujmović
Ruby #3 67

Highlights and Conclusions
• Ruby is a multi-paradigm language: it is good for procedural, functional and object oriented programming
• Comfortable: Ruby is a dynamically typed language – no type definitions before we start running code
• Rich: 98 standard libraries and 9000+ methods
• Relaxed approach to syntax – many alternative ways to achieve goals; no rigid rules
• Strictly object oriented – that yields rich control structures and flexibility in building objects
• Simplicity in defining and expanding classes
• Free and growing: web development
• Performance awareness: benchmarks, YARV
• Tools: debugger, profiler and much more
© Jozo Dujmović Ruby #3 68

Next steps
• Ruby on rails – web development
framework: http://www.rubyonrails.org
• Common Gateway Interface (CGI) web programming toolkit http://www.spice-of- life.net/cgikit/index_en.html
© Jozo Dujmović Ruby #3 69