Removing space between 1st and last name -- A basic/beginner .length problem


#1

I tried to google and everything is way beyond the scope of this exersize. The problem is simply ask for full name and use .length and then puts the number of characters in their name.
.chomp removes the trailing space at end of name, but what removes the space between the 1st and last name? My count always comes out 1 over.
Code:
puts “Please enter your full name:”
name = gets.chomp.length
puts “#{name}”

when run:
Please enter your full name:
Mickey Mouse
12

Thank you tofif!


#2

Hello @tofif,

The most elegant solution that I know is this one:

puts "Please enter your full name:"
name = gets.chomp
characters_number = name.gsub(/[\s+'-]/, '').length
puts "#{name} is #{characters} characters."

The magic is here:

formatted_name = name.gsub(/[\s+'-]/, '')

The idea here is to get the username, find all whitespace characters with a regular expression, and replace them (thanks to gsub!) with no space, so both names will be merged. After that, you could apply length method on that formatted name and you will get the exact number of characters.

Hope that will help you!