Instance variable creation | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Instance variable creation

What is the purpose/meaning of the second line in the code below? @age = 0 I don't understand why there is an instance variable @name declared inside the class but outside the method. What does this create? what is its scope and use? class Animal @age = 0 def initialize(name, age) @name = name @age = age end end

11th Nov 2018, 4:52 PM
Ana Lopez
Ana Lopez - avatar
2 Answers
+ 7
I think it sets an atribute age that is equal to 0 for every member of the class Animal and by adding @age=age you're saying that age can be different from 0 if specified (I quite forgot Ruby oop but this is what I think it is...)
11th Nov 2018, 5:22 PM
Uni
Uni - avatar
+ 1
This is an excellent question. Give me a few minutes to reply with a response that will hopefully be short and clear.
11th Nov 2018, 5:37 PM
David Carroll
David Carroll - avatar