I’m trying to write a program that takes the length of my first, middle, and last name, individually, and then adds the total amount of letters up in the end. My answer keeps on being 666 instead of 18. Here is the code I have written.
puts 'What is your first name?'
firstName = gets.chomp
realFirstName = firstName.length.to_i
puts 'What is your middle name?'
middleName = gets.chomp
realMiddleName = middleName.length.to_i
puts 'What is your last name?'
lastName = gets.chomp
realLastName = lastName.length.to_i
puts 'Did you know there are ' + realFirstName.to_s + realMiddleName.to_s + realLastName.to_s + ' letters in your name?'
Just wondering where I went wrong.
Since you’re converting the integers back into strings on the last line, you’re concatenating strings, not adding numbers. What you’re doing is:
Just don’t call
to_son the numbers and add them up prior instead:I’ve also used string interpolation to make it a bit easier to read.
There’s also no need to call
to_iafter callinglength, sincelengthalready returns an integer.