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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With