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 trialkabir k
Courses Plus Student 18,036 PointsQuestions about the Contact class
I have some questions about the Contact class we just created in Contact Class: Part 1
class Contact
attr_writer :first_name, :middle_name, :last_name
def first_name
@first_name
end
def middle_name
@middle_name
end
def last_name
@last_name
end
def full_name
full_name = first_name
if !@middle_name.nil?
full_name += " "
full_name += middle_name
end
full_name += ' '
full_name += last_name
full_name
end
end
jason = Contact.new
jason.first_name = "Jason"
jason.last_name = "Seifer"
puts jason.full_name
nick = Contact.new
nick.first_name = "Nick"
nick.middle_name = "A"
nick.last_name = "Pettit"
puts nick.full_name
Why are we not using the initialize method?
Why do we need methods for the instance variables, @first_name, @middle_name, and @last_name when we've already made them attribute writers?
And in the full_name method, why are we implicitly returning the full_name variable, and not explicitly returning it? Also, when should we implicitly return a value from a method? (as opposed to explicitly returning a value from the method)
2 Answers
Rafael Flores
Courses Plus Student 22,056 Points- The attr_writer method is a way to initialize. 2 and 3 have the same answer here in this exercise you are just learning different ways to do things. Do not get too hung up on those. In programming there is always many path to achieve the same. This is one way to get it done.
MOD NOTE: Moved from "Comment" to "Answer" (so it may be up-voted and/or marked as "Best Answer")
mkmk
15,897 PointsAlso, re: #3 -- Ruby will implicitly return the last line of a function block, so you do not need to write the word 'return'. You can write 'return' if you would like, it's just not necessary.
Bear in mind that explicitly returning in Ruby is more memory intensive and could result in a noticeable performance hit if you are explicitly returning on every function.
rowend rowend
2,926 Pointsmkmk there is a place to read about the fact of memory with return?