Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a string of names into a name with initials and last name

Tags:

string

ruby

I need to do the following with Ruby:

Turn this string of names "joseph jeremiah bloggs" into "J.J.Bloggs"

It has to work for any number of names with the last name always the full word and the other names initials.

I have the following code so far:

def initials(name)
  name.split.map(&:capitalize).join('.')
end

Which returns "Joseph.Jeremiah.Bloggs"

Is there a way to get the initials for the first two words?

like image 716
KVyas Avatar asked Oct 25 '25 04:10

KVyas


1 Answers

This is one way that follows your code:

def initials(name)
  *rest, last = name.split
  (rest.map{|e| e[0]} << last).map(&:capitalize).join('.')
end

Using the splat * makes rest collect all the names except the last.

like image 65
Yu Hao Avatar answered Oct 26 '25 21:10

Yu Hao