Ironruby.2.1 – Fundamentals (Class) Cont…

From the previous example, you noticed, all the variables declared inside the code is by default is private. If you want to access the class variables either you need to declare the getter/setter methods inside the class or make the class variable as public.

Lets look at the first approach or creating a getter/setter for a class variable.

class Person
def name #get method
@name
end

def initialize(name, age, sex)
@name = name
@age = age
@sex = sex
end

def sayName
puts @name
end
end

student = Person.new(“Joe”,30,”Male”)
puts student.name

In the above example the first part of the program, there is a method called name, which in turn return the private variable name. If you look at the last line of the code what we are doing is printing out the class variable itself to print the name, instead of calling the ‘sayName’ method.

I created the above code as class3.rb in my favorite notepad++ editor and fireup rbx and see what happens. Here is the result of the run;

class3.rb

Good, now you know how to create the getter (because you are asked ruby to get the private class variable). Now lets look at setter as well in the same code. Setter is a way to set a value of private variable in a class without exposing the variable itself. Getter and Setters are nothing more than a glorified methods which gives a way to access the class variables.

class Person
def name
@name
end
def name=(value)
@name=value
end

def initialize(name, age, sex)
@name = name
@age = age
@sex = sex
end
end

student = Person.new(“Joe”,30,”Male”)
puts “Name = ” + student.name
student.name=”John”
puts “After changing the Name, the new name is ” + student.name

In the above example (class4.rb) the first bold section is the method which sets the class local variable with the value assigned to it. The ‘value‘ is a reserved word which holds the value that is in the right hand side of the assignment. Towards the end of the program the second bold line is the actual setting of the value to the private class variable.

Now if we run the code the output will be like the following;

class4.rb

As you can see the first line of the ouput has the local variable name as Joe. It is because of the initializer method. The second line got the value of John after the call to the setter method.

As you can see it is easy to get and set the private variables in a class without exposing the class variable itself. But the real beauty of getter and setter is far beyond just setting or getting the private variable…

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google

No Responses so far »

Comment RSS · TrackBack URI

Say your words

You must be logged in to post a comment.