Including the first name string in first and last names
I need to do the following with Ruby:
Turn this string of names
"joseph jeremiah bloggs"
into"J.J.Bloggs"
It should work for any number of first names with a last name, always with the full name and other initials of the first names.
I have the following code:
def initials(name)
name.split.map(&:capitalize).join('.')
end
What returns "Joseph.Jeremiah.Bloggs"
Is there a way to get the initial values ββfor the first two words?
+3
source to share
4 answers
Updated solution (although this thread is closed, I still want to help others). I feel this solution is easier for new Ruby developers.
def initialize_name(name)
name = name.split(" ")
name.map {|n| n.equal?(name.last) ? n.capitalize : n[0].capitalize }.join(". ")
end
initialize_name "joseph jeremiah blogg" # => J. J. Blogg
Old solution
Here's what I came up with. Not the prettiest but it works, I'm going to try and make it the best for you.
joe = "joseph jeremiah blogg"
def initialize_name(name)
return_value = ""
name = name.split(" ")
name.each do |n|
if n.equal? name.last
return_value << "#{n.capitalize}"
else
return_value << "#{n[0].capitalize}. "
end
end
return_value
end
puts initialize_name joe # => "J. J. Blogg"
0
source to share