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 Build an Address Book in Ruby Class Design Phone Number Class

MaryAnn Eleanya
MaryAnn Eleanya
8,626 Points

I am not sure what a block of code is supposed to do.

https://teamtreehouse.com/library/build-an-address-book-in-ruby/class-design/phone-number-class

"I am struggling with a few lines of code from this video. I've attached the link to the video above and the code is also in the teacher's note."

def last_first
 last_first = last_name
    last_first += ", "
    last_first += first_name
    if !@middle_name.nil?
      last_first += " "
      last_first += middle_name.slice(0, 1)
      last_first += "."
    end
    last_first

"First, I am not really sure what the code above is supposed to do. There is also a similar version of it for the full_name variable."

 def to_s(format = 'full_name')
 case format
    when 'full_name'
      full_name
    when 'last_first'
      last_first
    when 'first'
      first_name
    when 'last'
      last_name
    else
      first_last
    end
  end

"Secondly, I know this code is supposed to turn the variable into strings but I've never seen it formatted this way before. I am also not sure what the word 'case format' means."

[MOD: edited code block - srh]

1 Answer

Steven Parker
Steven Parker
231,236 Points

The code in your first question builds up the "last_first" variable:

  • it starts with the contents of "last_name"
  • then it adds a comma and a space
  • then it adds the contents of "first_name"
  • then, only if "middle_name" is not empty, it adds a space and then the first letter from "middle_name"
  • finally, it adds a period to the end

In the second question, the word "case" begins a conditional based on the variable "format". It is compared to the term after each "when" to determine if the expression that follows it should be returned.