Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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