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

kabir k
kabir k
Pro 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

  def middle_name

  def last_name

  def full_name
    full_name = first_name
    if !@middle_name.nil?
      full_name += " "
      full_name += middle_name
    full_name += ' '
    full_name += last_name

jason =
jason.first_name = "Jason"
jason.last_name = "Seifer"
puts jason.full_name

nick =
nick.first_name = "Nick"
nick.middle_name = "A"
nick.last_name = "Pettit"
puts nick.full_name
  1. Why are we not using the initialize method?

  2. Why do we need methods for the instance variables, @first_name, @middle_name, and @last_name when we've already made them attribute writers?

  3. 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
Rafael Flores
Pro Student 20,534 Points
  1. 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.

rowend rowend
rowend rowend
2,923 Points

mkmk there is a place to read about the fact of memory with return?