Presentation is loading. Please wait.

Presentation is loading. Please wait.

Variables All variables hold object references

Similar presentations


Presentation on theme: "Variables All variables hold object references"— Presentation transcript:

1 Variables All variables hold object references
Similar to Java handles, but in Ruby there are no primitives Like Java, objects are garbage collected

2 Variable Scope Constants – defined in a class or a module 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; def anotherzero(array) newarray = Array.new(array.length); n = newarray.length - 1; newarray[i] = 0; array = newarray; n = 3; increment(n); puts n.to_s; array = [1, 2, 3]; zero(array); puts array.join(", "); anotherzero(array); What is the output? 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; msg = "bye" agent += 1; msg.upcase!; end foo(msg, agent) What is the output? Ruby Notes

7 Block Scope Example #!/usr/local/bin/ruby def foo(localvar1)
localvar2.downto(1) do |blockvar| puts "#{localvar1} #{localvar2} #{blockvar}" end foo(3) What is the output? Ruby Notes

8 Ruby classes Constructor method is called initialize
Objects are created by executing call: var = Classname.new(parameter(s)) initialize method automatically called and receives parameters passed to new Parameters are local to the initialize method var 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 class String #whatever I define here is added to #the existing String class end Executing a class definition causes a Class object to be created and assigned to a constant called classname the class definition above causes: String = Class.new(); Ruby Notes

10 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

11 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

12 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}"; Ruby Notes

13 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 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 Ruby Notes

14 Methods, continued Methods can be private, protected or public
public – can be called from anywhere in the code; by default, class 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

15 Methods, continued class Aclass
public #methods below here, up to private, are public def initialize() . end def foo() private #goo is private def goo() Ruby Notes

16 Instance Methods Act upon instances of the class def instanceMethod(…)
end Ruby Notes

17 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

18 Instance variables Instance variables start with 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 a 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

19 #!/usr/local/bin/ruby class Class attr_reader :teacher, :name;
def initialize(teacher, name, size) @teacher = teacher @name = name @size = size 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 Ruby Notes

20 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 t = Time.new() t.minutes = 453 To the user of the class, it looks like minutes is a writeable attribute Ruby Notes

21 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

22 class CSClasses = 0; def initialize() @classes = Array.new() end def addClass(teacher, name, size) aClass = OneClass.new(teacher, name, size) @classes.insert(0, aClass); += 1; def teacherCount(t) count = 0; @classes.each do |c| if c.teacher == t count += 1 return count def CSClasses.deptCount #!/usr/local/bin/ruby class OneClass def initialize(t, n, s) @teacher = t @name = s @size = n end attr_reader :teacher, :name, :size;

23 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

24 Inheritance, continued
Name of the constructor is called initialize 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

25 #!/usr/local/bin/ruby
class GrandParent def initialize puts "GrandParent Constructor" end class Parent1 < GrandParent def initialize() puts "Parent1 Constructor"; class Parent2 < GrandParent super(); puts "Parent2 Constructor"; class Child1 < Parent1 puts "Child1 Constructor"; class Child2a < Parent2 def initialize() super(); puts "Child2 Constructor"; end class Child2b < Parent2 child1 = Child1.new; puts "\n"; child2a = Child2a.new; child2b = Child2b.new; What is the output?

26 type + " with attributes " + attributes + " is " + @area.to_s;
class Polygon def initialize @area = 0 end def printArea puts "The area of " + type + " with attributes " + attributes + " is " + @area.to_s; class Rectangle < Polygon def initialize(height, width) super(); @height = height; @width = width; end def type "rectangle" def attributes "height = " + " width = " def calcArea() @area Ruby Notes

27 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

28 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

29 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

30 #!/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 = #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 Ruby Notes

31 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 def areaUsingClassMethod() #call the ClassMethod in Math Module 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}"

32 Here's same example, but Math is used as a mixin
#!/usr/local/bin/ruby module Math MYpi = end class Circle include Math attr_reader :radius def initialize(r) @radius = r def area() MYpi c = Circle.new(2.3) puts "Area of circle with radius #{c.radius} = #{c.area}" Ruby Notes

33 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

34 class Professor < Person
def initialize(name) name = "Professor " + name; super(name) end def grade(student) student.grade('A') prof = Professor.new('Cindy Norris'); stud = Student.new('Jill Guy'); prof.grade(stud); puts prof.name + " assigned " + stud.name + " the grade " + stud.thegrade; #!/usr/local/bin/ruby class Person def initialize(name) @name = name; end attr_reader :name; class Student < Person name = "Student " + name; super(name) def grade(thegrade) @thegrade = thegrade attr_reader :thegrade

35 More examples List parent class with stack and queue subclasses
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)

36 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

37 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


Download ppt "Variables All variables hold object references"

Similar presentations


Ads by Google