Sunday, February 20, 2011

Ruby_here_and_there_5 - def initialize

What def initialize does?

def initialize is used to define a  variable, the below examples demonstrate how to initialize an object variable.


An object variable is prefixed with "@"

For example,

there are two objects a and b

the change "a" makes to variable is applicable within "a"

class Person
  def initialize (name)
    @name = name
  end
  def england
    puts  "#{@name}"
  end
end
 
  a=Person.new("dickens")
  a.england
Output is "dickens"
for object "a" @name is "dickens"

class Person
  def initialize (name)
    @name = name
  end
  def england
    puts  "#{@name}"
  end
end
 b=Person.new("Cooper")
 b.england
For object "b" @name is "Cooper"
What happens if I assign the value to name during initialization ?
class Person
  def initialize (name = "Newman")
    @name = name
  end
  def england
    puts  "#{@name}"
  end
end
c=Person.new
c.england

Output is "Newman"
Object "c" is not changing the varibale "@name"
so output will be "@name"'s original value as initialized "Newman"

But if you call the  @name with a value  for the  new object, @name then assumes the value directed by the object.
class Person
  def initialize (name = "Newman")
    @name = name
  end
  def england
    puts  "#{@name}"
  end
end
d=Person.new("Peter")
d.england
Output is "Peter
" ,
So, @name assumed the value of Peter

Class variables have a scope across the class, not only to the object of the class

They are prefixed with "@@"

Example :

class Square
  @@length = 10
  def initialize(hight)
    @hight=hight
  end
 
  def self.length
    @@length
  end

def squareadd
  @hight
  end
  end
"@@length" is a class variable, and it is directly accessed referencing to the class, not to the object

i.e. Class:ClassVariable

puts Square.length

Output is "10"

where as @hight is an object variable, which is referenced with the object "a"

a=Square.new(5)
puts a.squareadd

Outputs is "5"

No comments:

Post a Comment