Posts Tagged class
Class is an object
Are you really into a position to justify these outputs??
If so, means your OOP concepts in RUBY is clear else ……..
class Acer // Jacobian Code end Acer.class > Class Acer.superclass > Object Class.superclass> Module 2.class > Fixnum 2.988888.class > Float -2.class > Fixnum "2".class > String 0x22.class > Fixnum Class.class > Class nil.class > NilClass self.class > Object Object.class > Class Object.type > Class Time.class > Class Time.now.class > Time
Add comment April 6, 2008
Instance var Vs Class var
# class varibale starts with @@
# Must be initialized before they are used
# A class variable is shared among all objects of a class
# There is only one copy of a particular class variable for a given class
# It is also accessible to the class methods
#Sometimes a class needs to provide methods that work without being tied to any particular object.
# For example the “new” method creates a new object but is not itself associated with a particular application.
# And you are calling them as App.new() rather than calling as obj1.new() or obj2.new()
#Hence “new” will be said as a class method not an instance method.
#class methods sprinkled throughout the Ruby librariesclass methods sprinkled throughout the Ruby libraries. other eg File.delete associated with File class
# $super_count – global variable – Can access anybody
# @@count – class varibles – Change will be reflected to all
# @call – instance variobles – Change will be reflected in only concern method
# callme – instance method -
# new – class method
#Class methods are defined by placing the class name and a period in front of the method name.
class App
$super_count = 111
@@count = 0
def initialize (caller)
@call = caller
end
# instance method
def callme
p “called using #{@call}”
@@count+=1
end
# class method
def App.callmetoo
p “called using callmetoo”
@@count+=1
end
end
obj1 = App.new(”OBJECT1?)
obj2 = App.new(”OBJECT2?)
p obj1.callme
p obj2.callme
p App.callmetoo
p $super_count #can be access outside the class
#p App.@@count #cant access outside the class
OUTPUT
“called using OBJECT1?
1
“called using OBJECT2?
2
“called using callmetoo”
3
111
Add comment March 22, 2008