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


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 splat *

does rest

collect all names except the last one.

+4


source


You can do it like this:

"joseph jeremiah bloggs"
.gsub(/\w+\s*/){|s| ($'.empty? ? s : "#{s[0]}.").capitalize}                    #'
# => "J.J.Bloggs"

      



or

"joseph jeremiah bloggs"
.gsub(/\w+\s+/){|s| "#{s[0].upcase}."}.sub(/\w+\z/, &:capitalize)
# => "J.J.Bloggs"

      

+2


source


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


def initials(name)
  (name.split.drop(1).map do |subname|
    subname[0].upcase
  end + [name.split.last]).join('.')
end

initials("Bob Smith Jones")

      

-1


source







All Articles