DEV Community

loading...

Discussion on: Daily Challenge #38 - Middle Name

Collapse
tanguyandreani profile image
Tanguy Andreani

Ruby solution

I just changed a few things in a similar function from singl.page. Doesn’t use join(). Works when only a single name is provided.

def middle_names(fullname)
  String.new.tap { |result|
    fullname.split(' ').then { |words|
      words.map.with_index { |word, i|
        case i
        when 0
          result << word.capitalize
        when words.length - 1
          result << ' '
          result << word.capitalize
        else # middlename
          result << " #{word[0].upcase}."
        end
      }
    }
  }
end