kabir kPro Student 18,036 Points
Questions 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)
Rafael FloresPro Student 20,534 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")
Also, 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.