Ironruby.2.1 – Fundamentals (Class) Cont…

In the previous post we saw how to create a simple class and how to access the class variables inside the class methods. In this example, we are going to see how to get or set the values of the object variables and what are the limitations you need to know.

Following code is exactly same as the last one but in this we will try to access the object variable from outside the class and see what happens;

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

def sayName
puts @name
end
end

student = Person.new(“Joe”,30,”Male”)
student.name = “John” #in this declaration name is defined private
student.sayName()

[As I mentioned before, I use Notepad++ to write my ruby code. I type in this code and save it as class2.rb and I use this file to run the ruby code] Now we tell rbx to run our class2.rb code and the output will look like the following;

class2.rb

as you can see from the output, ironruby is complaining that, there is no method or local variable defined as name. it is an expected result based on how we coded the class. We create only two methods, one is initialize which does not but set the initial values for the variables in the class. The second method does nothing but display the local instance variable initialized in the previous method.

It is very important to note that we did not define explicitly the name, age or sex variables, but when you refer a variable inside the class definition with @, that means it will be defined for you to access as private variable only inside the class. This is the default. If you would like to expose these variables outside the class then you need to explicitly define your intend as in the following example.

From the above example, only thing I want to point out is that, if you define a variable inside the class with @ then it becomes instance variable and only available to all class methods but will not be available to change like we did in line 14 [student.name = “john”, in this line you are outside the class definition]. In other words, if you define a variable with @ by default it is declared as private but there things you can do to make it available and we will see that in the following examples….

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.