Learning Ruby Classes
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 class variable (declared within a class) name starts with two ''at'' signs followed by a name 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
class Person def initialize( name, 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 indicates class variables
fred.to_s class Person def to_s born on 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
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]
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.
class Person def end # of name. def end # of dob. def end # of nationality. end # of Person. fred.name fred.to_s fred.dob Class Get Methods
class Person def set_name( name = name end # of set_name. def set_dob( dob = dob end # of set_dob. def set_nationality( nationality = nationality end # of set_nationality. end # of Person. fred.name fred.set_name( "Fred Reginald Jones" ) fred.to_s Class Set Methods
class Person attr_reader :name, :dob, :nationality attr_writer :name, :dob, :nationality def initialize( name, dob, nationality = = = nationality end # of initialize. def to_s born on 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
class Person attr_accessor :name, :dob, :nationality reading and writing of attribute def initialize( name, dob, nationality = = = nationality end # of initialize. def to_s born on 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
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
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
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
Code Eval? class Module def trace_attr(sym) self.module_eval %{ def #{sym} printf "Accessing %s with value end } end class Dog trace_attr :name def = string end Dog.new("Fido").name # => Accessing name with value "Fido" d = Dog.new("Toby") puts "how is #{d} "
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.
class Color def ||= {} assign if not end def end def {|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