Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Variables • All variables hold object references • Similar to Java handles, but in Ruby there are no primitives • Like Java, objects are garbage collected Recall Ruby naming convention • Local variables, method parameters, method names start with lower case letter or underscore • Class names, constants start with an uppercase • Global variables start with a $ • Instance variables start with an @ • Class variables start with @@ • Beyond the initial character, name can be any combination of letters, digits, and underscores (however, can not follow an @ with a digit) Variable Scope • Constants – defined in a class or a module (collection of related code) can be accessed unadorned anywhere within the class or module; outside, they can be accessed using scope :: operator • Constants defined outside of a class or module can be accessed unadorned • Global variables (declared outside any class or module) are available throughout a program • Class variables can only be accessed within the class (or module); but, you can provide accessor methods Ruby Notes 3 Variable Scope • Instance variables can only be accessed within the class or subclasses (but you can make them attributes or provide accessor methods) • Local variables – scope is the immediately enclosing block, method definition, class definition, module definition or top level program • Method parameters are variables local to the method Ruby Notes 4 Parameter Passing • all variables are references to objects • parameters are passed by value (references are passed by value) – some mistakenly call this pass by reference Ruby Notes 5 Parameter Passing Example #!/usr/local/bin/ruby def increment(n) n = n + 1; end def zero(array) n = array.length - 1; n.downto(0) do |i| array[i] = 0; end end def anotherzero(array) newarray = Array.new(array.length); n = newarray.length - 1; n.downto(0) do |i| newarray[i] = 0; end array = newarray; end n = 3; increment(n); puts n array = [1, 2, 3]; zero(array); puts array.join(", "); array = [1, 2, 3]; anotherzero(array); puts array.join(", "); What is the output? http://www.cs.appstate.edu/~can/classes/3490/Ruby/callbyval.rb Ruby Notes 6 Variable scope and parameter passing example #!/usr/local/bin/ruby msg = "hello"; agent = 99; def foo(msg, agent) puts msg + " " + agent.to_s; agent += 1; msg.upcase!; puts msg + " " + agent.to_s; end What is the output? puts msg + " " + agent.to_s; foo(msg, agent) puts msg + " " + agent.to_s; http://www.cs.appstate.edu/~can/classes/3490/Ruby/scope.rb Ruby Notes 7 Block Scope Example #!/usr/local/bin/ruby def foo(localvar1) localvar2 = 3; localvar2.downto(1) do |blockvar| puts "#{localvar1} #{localvar2} #{blockvar}" end puts "#{localvar1} #{localvar2} #{blockvar}" end What is the output? foo(3) http://www.cs.appstate.edu/~can/classes/3490/Ruby/blockscope.rb Ruby Notes 8 Ruby classes • Constructor method is called initialize • Objects are created by executing call: – obj = Classname.new(parameter(s)) – initialize method automatically called and receives parameters passed to new – Parameters are local to the initialize method – obj is a reference to an object (not an actual object) Ruby Notes 9 Classes • Class definition used to create a new class or extend an existing class • This program shows how to extend the built-in String class #!/usr/local/bin/ruby class String def upperreverse self.reverse.upcase end end str = String.new("hello") str = str.upperreverse puts str #self is Java's this Ruby Notes 10 Classes • Executing a class definition causes a Class object to be created and assigned to a constant called classname • Given a file containing: class Car #body of Car class goes here end • When Ruby parses the file, it will first create a Class object with the name Car – in other words, the class definition above causes: Car = Class.new(); Ruby Notes 11 Classes • when a constructor is invoked, it uses the constant that was created by parsing the file car = Car.new() – Car is a reference to a Class object – Car.new() is a call to the new method in the Class class – a property of the Car Class object is the actual class Car code – Car.new will cause the initialize in the Car class Ruby Notes 12 to be called Methods • Instead of saying “method call,” Ruby types refer to this process as sending a message to a receiver stk.push(3) #stk is the receiver, push is the message • The last expression evaluated is what is returned by the method so often no explicit return is needed • No return type specified • Parameters have no type information so you can pass anything to a method, but if you treat it improperly, you’ll get an error Ruby Notes 13 Methods, continued • Don’t use braces – Method starts with def – Method ends with end • Default parameters can be provided def foo(n1 = 0, n2 = 3) . . end Ruby Notes 14 Methods can return more than one value #!/usr/local/bin/ruby def increment(n) return n, n + 1; end n = 3; n, ninc = increment(n); puts "#{n} incremented is #{ninc}"; http://www.cs.appstate.edu/~can/classes/3490/Ruby/return.rb Ruby Notes 15 Methods, continued • Methods can also be passed a block in addition to other parameters – Blocks are called from the method with a yield statement – Parameters can be sent to the block http://www.cs.appstate.edu/~can/classes/3490/Ruby/block.rb • You can pass multiple parameters to a method by prefixing formal parameter with a * def foo(*a) #all arguments passed to foo are #bundled into an array http://www.cs.appstate.edu/~can/classes/3490/Ruby/params.rb Ruby Notes 16 Methods, continued • Methods can be private, protected or public – public – can be called from anywhere in the code; by default, methods are public – protected – can be called only within the class in which the method is defined or within derived classes – private – can be called only within the class in which the method is defined – methods are defined to be public, protected or private by inserting public, protected or private key word Ruby Notes 17 Methods, continued class Aclass public #methods below here, up to private, are public def initialize() . end def foo() . end private #goo is private def goo() . end end Ruby Notes 18 Instance Methods • Act upon instances of the class def instanceMethod(…) end Ruby Notes 19 Class Methods • Method that is not tied to an instance of the class in which they are declared • In Java/C++, we create these by declaring them to be static • In Ruby, they are created by prefixing the method name with the class name and a period def Classname.methodname(…) Ruby Notes 20 Instance variables • Instance variables start with an @ sign, don’t need to be declared and are protected • The visible (readable and/or writable) instance variables are called an object’s attributes • attr_reader – shortcut for creating methods for reading attributes • attr_writer – shortcut for creating methods for writing to attributes • attr_accessor – shortcut for creating two methods – one for reading and one for writing to an attribute Ruby Notes 21 Attribute Example #!/usr/local/bin/ruby class Example attr_reader :readMe attr_writer :writeMe attr_accessor :readWriteMe def initialize @readMe = 4 @writeMe = 5 @readWriteMe = 6 end end #see use of symbols! myexample = Example.new #shows allowable operations puts myexample.readMe #read myexample.readMe myexample.writeMe = 7 #write to myexample.writeMe myexample.readWriteMe = 8 #write to myexample.readWriteMe puts myexample.readWriteMe #read myexample.readWriteMe Ruby Notes 22 Another Example #!/usr/local/bin/ruby class Class attr_reader :teacher, :name; def initialize(teacher, name, size) @teacher = teacher @name = name @size = size end end cs3490 = Class.new("Cindy Norris", "CS 3490", 21) puts cs3490.name puts cs3490.teacher #no accessor method for size, so can't: puts cs3490.size #can't modify cs3490.name, cs3490.size, cs3490.size http://www.cs.appstate.edu/~can/classes/3490/Ruby/class.rb Ruby Notes 23 Virtual Attributes • Putting an = at the end of a method allows the method to be used as a target of an assignment class Time def minutes=(newmin) @hours = newmin / 60.0 end end t = Time.new() t.minutes = 453 • To the user of the class, it looks like minutes is a writeable attribute Ruby Notes 24 Class Variables • Shared among all objects of a class • Start with @@ • Initialized with an assignment statement within the body of the class definition (outside of a method definition) Ruby Notes 25 #!/usr/local/bin/ruby class OneClass def initialize(t, n, s) @teacher = t @name = s @size = n end attr_reader :teacher, :name, :size; end class CSClasses @@deptCount = 0; def initialize() @classes = Array.new() end def addClass(teacher, name, size) aClass = OneClass.new(teacher, name, size) @classes.insert(0, aClass); @@deptCount += 1; end def teacherCount(t) count = 0; @classes.each do |c| if c.teacher == t count += 1 end end return count end def CSClasses.deptCount @@deptCount end end http://www.cs.appstate.edu/~can/classes/3490/Ruby/CSClasses.rb 26 Inheritance • Specified by: class SubClassName < SuperClassName • super can be used to call a super class method of the same name - Super without parens causes the same parameters to be passed to the parent method as were received by the child method • Default parent of every class is the Object class - Object class contains 35 instance methods Ruby Notes 27 Inheritance, continued • Construction of an object will cause an initialize function to be searched for starting with the class of the object just created and then search upward through the ancestors • only one constructor will be executed unless the constructor includes a call to super Ruby Notes 28 #!/usr/local/bin/ruby class Child2a < Parent2 class GrandParent def initialize() def initialize super(); puts "GrandParent Constructor" puts "Child2 Constructor"; end end end end class Parent1 < GrandParent class Child2b < Parent2 def initialize() end puts "Parent1 Constructor"; end child1 = Child1.new; end puts "\n"; class Parent2 < GrandParent child2a = Child2a.new; def initialize() puts "\n"; super(); child2b = Child2b.new; puts "Parent2 Constructor"; puts "\n"; end end class Child1 < Parent1 What is the output? def initialize() puts "Child1 Constructor"; super(); end end http://www.cs.appstate.edu/~can/classes/3490/Ruby/constructors.rb class Polygon def initialize @area = 0 end def printArea puts "The area of " + type + " with attributes " + attributes + " is " + @area.to_s; end end class Rectangle < Polygon def initialize(height, width) super(); @height = height; @width = width; end def type "rectangle" end def attributes "height = " + @height.to_s + " width = " + @width.to_s end def calcArea() @area = @height * @width; end end Ruby Notes 30 Inheritance, continued • Supports only single inheritance but a class can include the functionality of any number of mixins • A mixin is a module that has been included by a class Ruby Notes 31 What is a module? • Similar to a Java abstract class in that it can’t be instantiated • Can contain instance methods, class methods, class variables, instance variables and constants Ruby Notes 32 How are modules used? • Module constants can be accessed by prefixing constant by name of module and :: – ModuleName::CONSTANT • Module class methods can be called by prefixing method name by the class name and a dot – ModuleName.methodname(..) • Or, modules can be included by a class – Everything in the module becomes a member of the class Ruby Notes 33 #!/usr/local/bin/ruby #This example shows how to define and use a module #Since this only has constants and class methods, it doesn't #need to be a "mixin" module Math #you can access MYpi as Math::Mypi MYpi = 3.141592654 #but to show you how to call module methods, I include #this class method (notice class methods are prefixed by #classname and a dot) def Math.getPI() return MYpi end end Ruby Notes 34 class Circle attr_reader :radius def initialize(r) @radius = r end def areaUsingConstant() #prefix constants in the module with the name of the module #and :: Math::MYpi * @radius * @radius end def areaUsingClassMethod() #call the ClassMethod in Math Module Math.getPI()* @radius * @radius end end c = Circle.new(2.3) puts "Area of circle with radius #{c.radius} = #{c.areaUsingConstant}" puts "Area of circle with radius #{c.radius} = #{c.areaUsingClassMethod}" http://www.cs.appstate.edu/~can/classes/3490/Ruby/circle.rb 35 Here's same example, but Math is used as a mixin #!/usr/local/bin/ruby module Math MYpi = 3.141592654 end class Circle include Math attr_reader :radius def initialize(r) @radius = r end def area() MYpi * @radius * @radius end end c = Circle.new(2.3) puts "Area of circle with radius #{c.radius} = #{c.area}" Ruby Notes 36 Polymorphism • Ruby types call a “method call” sending a message to a receiver • Messages to method bodies are dynamically bound • If an appropriate method can not be found in the chain of inheritance, an error (Object#method_missing) occurs Ruby Notes 37 #!/usr/local/bin/ruby class Person def initialize(name) @name = name; end attr_reader :name; end class Student < Person def initialize(name) name = "Student " + name; super(name) end def grade(thegrade) @thegrade = thegrade end attr_reader :thegrade end class Professor < Person def initialize(name) name = "Professor " + name; super(name) end def grade(student) student.grade('A') end end prof = Professor.new('Cindy Norris'); stud = Student.new('Jill Guy'); prof.grade(stud); puts prof.name + " assigned " + stud.name + " the grade " + stud.thegrade; http://www.cs.appstate.edu/~can/classes/3490/Ruby/person.rb 38 More examples • List parent class with stack and queue subclasses http://www.cs.appstate.edu/~can/classes/3490/Ruby/list.rb • Similar example, but the list is a module (can't create an instance of it) and is used as a mixin (it becomes part of the classes that use it) http://www.cs.appstate.edu/~can/classes/3490/Ruby/listMixin.rb 39 Type System • Ruby uses duck typing – type of the variable is determined by what it can do – Duck typing is dynamic – type is determined at run time and can change during run time Ruby Notes 40 Is there more to Ruby? • Yes, loads! – – – – – – – – – Exception handling Threads and processes Unit testing Namespaces Ruby debugger RDoc for creating ruby documentation Using Ruby for web applications (Rails) Graphics Using Ruby in conjunction with other languages (C, TK, Perl) – Ruby reflection Ruby Notes 41