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 trial

Ruby Ruby Blocks Working With Blocks Implementing Block Methods

Ieva Salte
Ieva Salte
15,356 Points

does 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

No, 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

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).