Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialIeva Salte
15,356 Pointsdoes array in the class MyArray needs not be denoted by @array throughout the class?
does array in the class MyArray needs not be denoted by @array throughout the class?
1 Answer
Andrei Fecioru
15,059 PointsNo, in this particular case it's not necessary to use the @ sign because the appropriate reader accessor was declared at the beginning of the class:
class MyArray
attr_reader :array
With this declaration in place, the Ruby interpreter will automatically synthesise a method for you (behind the scenes). It's something equivalent to the following method definition:
class MyClass
def array
@array
end
So, we no longer need to place the @ sign in from of the array
identifier. It's not wrong to do that though, but it's no longer necessary because you can just as well access the instance variable though the accessor method.
Note that the only place where you actually need to use the @ sign is inside the initialize
method because you need to explicitly declare and allocate the iVar in the first place. The attr-reader
syntax will not do that for you automatically (it will only generate the accessor method).