0

I'm making a simple Ruby program to add the letters of a person's full name, but I don't know how to add the variables in the code.

puts "What's your first name?"
first = gets.chomp
puts "What's your middle name?"
middle = gets.chomp
puts "What's your last name?"
last = gets.chomp

puts "You have " + first.length.to_s + middle.length.to_s + last.length.to_s + " letters in your name."

If I put a name like "John Jacob Smith", I get "You have 455 letters in your name" instead of "You have 14 letters in your name".

4 Answers 4

3
puts "You have " + first.length.to_s + middle.length.to_s + last.length.to_s + " letters in your name."

first.length is 4 (a number), because "john" has 4 letters.

first.length.to_s is "4" (a string) because you turned the number into as string - too early.

In the rest of your code, you 'add' two other strings to it, to get "455"

4 + 5 = 9        # what you want
"4" + "5" = "45" # what you got
Sign up to request clarification or add additional context in comments.

Comments

2
puts "You have " + (first.size + middle.size + last.size).to_s + " letters in your name."
# or
puts "You have #{first.size + middle.size + last.size} letters in your name."

or little more "Rubyish"

puts "You have " + [first, middle, last].inject(0){|s,w| s+=w.size}.to_s + " letters in your name."

Comments

2

Try this: puts "You have " + (first.length + middle.length + last.length) + " letters in your name."

Comments

1

That's because you're adding actual string representations of numbers instead of numbers thembselves. Check the @fl00r's answer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.