Presentation is loading. Please wait.

Presentation is loading. Please wait.

Learning Ruby Classes. Variables Variables in Ruby can contain data of any type. You can use variables in your Ruby programs without any declarations.

Similar presentations


Presentation on theme: "Learning Ruby Classes. Variables Variables in Ruby can contain data of any type. You can use variables in your Ruby programs without any declarations."— Presentation transcript:

1 Learning Ruby Classes

2 Variables Variables in Ruby can contain data of any type. You can use variables in your Ruby programs without any declarations. Variable name itself denotes its scope (local, global, instance, etc.). A local variable (declared within an object) name consists of a lowercase letter (or an underscore) followed by name characters An instance variable (declared within an object always "belongs to" whatever object self refers to) name starts with an ''at'' sign (''@'') followed by a name (@sign, @_, @Counter). A class variable (declared within a class) name starts with two ''at'' signs (''@@'') followed by a name (@@sign, @@_, @@Counter). A class variable is shared among all objects of a class. Only one copy of a particular class variable exists for a given class. Global variables start with a dollar sign (''$'') followed by name characters. A global variable name can be formed using '‘$'' followed by any single character ($counter, $COUNTER, $-x). Ruby defines a number of global variables that include other punctuation characters, such as $_ and $-K

3 class Person def initialize( name, dob, nationality ) @name = name @dob = dob @nationality = nationality end # of initialize. end # of Person. fred = Person.new( 'Fred Jones', '24/05/1950', :Irish ) puts fred puts fred.methods.sort puts fred.instance_variables Creating Classes Manually @ indicates class variables

4 fred.to_s class Person def to_s "#@name born on #@dob (#@nationality)" end # of to_s. end # of Person. fred.to_s Classes to Strings - Dynamically! We have added to_s AFTER already finishing the definition for class

5 Open Classes Methods can be added to classes at any point … even built in classes class Integer def even? (self % 2) == 0 end p (1..10).select { |n| n.even? }  [2, 4, 6, 8, 10]

6 inspect: Returns a string containing a human- readable representation of obj. If not overridden, uses the to_s method to generate the string (nice as prints array as [2, 4, 6, 8, 10] ) For each object, p directly writes anObject.inspect followed by the current output record separator to the program's standard output.

7 class Person def name @name end # of name. def dob @dob end # of dob. def nationality @nationality end # of nationality. end # of Person. fred.name fred.to_s fred.dob Class Get Methods

8 class Person def set_name( name ) @name = name end # of set_name. def set_dob( dob ) @dob = dob end # of set_dob. def set_nationality( nationality ) @nationality = nationality end # of set_nationality. end # of Person. fred.name fred.set_name( "Fred Reginald Jones" ) fred.to_s Class Set Methods

9 class Person attr_reader :name, :dob, :nationality attr_writer :name, :dob, :nationality def initialize( name, dob, nationality ) @name = name @dob = dob @nationality = nationality end # of initialize. def to_s "#@name born on #@dob (#@nationality)" end # of to_s. end # of Person. tom = Person.new( "Thomas", "26/05/1945", :Irish ) dick = Person.new( "Richard", "15/02/1980", :English ) harry = Person.new( "Harold", "02/11/1975", :American ) people = [ tom, dick, harry ] people.each { |person| puts person.to_s } Working Even More Less

10 class Person attr_accessor :name, :dob, :nationality  reading and writing of attribute def initialize( name, dob, nationality ) @name = name @dob = dob @nationality = nationality end # of initialize. def to_s "#@name born on #@dob (#@nationality)" end # of to_s. end # of Person. tom = Person.new( "Thomas", "26/05/1945", :Irish ) dick = Person.new( "Richard", "15/02/1980", :English ) harry = Person.new( "Harold", "02/11/1975", :American ) people = [ tom, dick, harry ] people.each { |person| puts person.to_s } Working Even Less

11 More... Ruby So Far Creating classes in Ruby is almost too easy The attr_reader and attr_writer and attr_accessor shortcuts are especially handy Of course, as Ruby supports OO, classes can inherit from other classes (and from more than one when you use mixins) Public, Protected and Private access controls are also available Chapter 3 of The PickAxe has all the details

12 Singleton methods Singleton methods are defined on individual objects, not classes. class Dog end rover = Dog.new fido = Dog.new def rover.speak puts "Red Rover" end rover.speak  "Red Rover" fido.speak  NoMethodError

13 Hooks allow the user to gain control at interesting moments during the execution of a program. method_added is predefined hook class MyClass def MyClass.method_added(name) puts "Adding Method #{name}" end def joy puts "HAPPY DAY" end t = MyClass.new puts “howdy ho” class MyClass def another end Adding Method joy howdy ho Adding Method another

14 Code Eval? class Module def trace_attr(sym) self.module_eval %{ def #{sym} printf "Accessing %s with value %s\n", "#{sym}", @#{sym}.inspect @#{sym} end } end class Dog trace_attr :name def initialize(string) @name = string end Dog.new("Fido").name # => Accessing name with value "Fido" d = Dog.new("Toby") puts "how is #{d} "

15 Enumerated Type – Ruby doesn’t have them class Color BLUE=1 RED=2 GREEN=3 YELLOW=4 ORANGE=5 PURPLE=6 end Fast way of associating name with value #paint_the_car(Color::YELLOW) puts Color::YELLOW 15 The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.

16 class Color def Color.add_item(key,value) @hash ||= {}  assign if not defined @hash[key]=value end def Color.const_missing(key) @hash[key] end def Color.each @hash.each {|key,value| yield(key,value)} end Color.add_item :BLUE, 1 Color.add_item :RED, 2 Color.add_item :YELLOW, 3 Color.add_item :GRAY, 4 end #That’s it! We can now use our enum : #my_color = Color::RED if some_condition #And we can loop Color.each do |key,value| puts "my colors are ", key, value end 16


Download ppt "Learning Ruby Classes. Variables Variables in Ruby can contain data of any type. You can use variables in your Ruby programs without any declarations."

Similar presentations


Ads by Google