Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Ruby%20On%20Rails%20Interview%20Questions%20and%20Answers

Question: How to define Instance variables?
Answer:

Instance variables are defined using single @ symbol.

@foo = "Hello"

Within a class they can be declared as below:

class Animal
 attr_accessor :name, :age
end

Next you can query an object instance to find which instance variables it has.

anim = Animal.new
anim.instance_variables 
=> [ ]
anim.name="John"
anim.age = 3
 => [:@age, :@name] 

In the above case we did not put the @ symbol before the instance variables but it is implied. 

Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook