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 Objects and Classes Variables and Methods Instance Variables and Local Variables

When creating an instance variable for a method, why doesn't Jason adds it to the initialize method?

When Jason creates the first_and_middle_name function he also defines an attr_reader :first_and_middle_name so that we can access the variable publicly.

Why doesn't he needs to define the variable in the initializer method as with first_name, last_name etc..

Thanks!

1 Answer

Not sure if this answers your question but you are on the right track. First attr_reader automatically creates a first_and_middle_name method that just returns the value of first_and_middle_name. Ruby does this behind the seems and it'll look something like:

def first_and_middle_name
  @first_and_middle_name
end

The question is where does that instance variable come from. Well, you are right that it could (and maybe should) be set in the initializer, since you have all the data there to build it. You could do something like:

def initialize(title, first_name, middle_name, last_name)
  @title = title
  @first_name = first_name
  @middle_name = middle_name
  @last_name = last_name
  @first_and_middle_name = @first_name + " " + @middle_name
end

But instead, Jason builds it in the full_name function (notice that the last line of the above initialize method is the same as the line from the video).

So before you call the first_and_middle_name function, @first_and_middle_name doesn't exist! You can try it out by modifying the code like:

name = Name.new("Mr.", "Jason", "", "Seifer")
# puts name.full_name_with_title
puts name.first_and_middle_name.inspect # => nil

If you run that, it'll return nil because full_name was never called to initialize the value. In short, it's somewhat of an oversight made in order to get the main point of the video across.