Ruby Build an Address Book in Ruby Class Design Contact Class: Part 1

Shreemangal Sethi
Shreemangal Sethi
11,886 Points

Instance Variable

I want to know when creating the full_name method - in the string interpolation why isn't "@" used before the variable. I created this rb file on atom and my method looks like this

def full_name "#{@first_name} #{@middle_name} #{@last_name}" end

and it returns the full name - "Shreemangal Sethi", with an extra space.

But when i do def full_name "#{first_name} #{middle_name} #{last_name}" end

i get this error

in full_name': undefined local variable or methodmiddle_name' for #<Contact:0x00007f92120c40a8> (NameError) Did you mean? midddle_name middle_name=

why is that?

1 Answer

well, when you refer to #{first_name}, the interpreter thinks that's a local variable. When it does not find that on the function you created, it errors out even if there is a instance variable of the same name. the interpolation needs to be specifically told it is an instance variable by the use of "@" before the variable's name.