Hi,
I am am trying to add the characters of my name together but I am
getting the error
‘no implicit conversion of Fixnum into String,’
puts “What is your first name?”
first = gets.chomp
puts “What is your middle name?”
middle = gets.chomp
puts “What is your last name?”
last = gets.chomp
puts ‘You have’ + first.length.to_i + middle.length.to_i +
last.length.to_i + ‘letters in your name’
I’ve also tried
puts “What is your first name?”
first = gets.chomp.to_i
puts “What is your middle name?”
middle = gets.chomp.to_i
puts “What is your last name?”
last = gets.chomp.to_i
puts ‘You have’ + first.length + middle.length + last.length + ‘letters
in your name’
with the error
‘undefined method `length’ for 0:Fixnum (NoMethodError)’
puts “What is your first name?”
first = gets.chomp
puts “What is your middle name?”
middle = gets.chomp
puts “What is your last name?”
last = gets.chomp
complete_name = first + middle +last
.length works as well
puts “You have #{complete_name.length} letters in your name.”
Why do you guys first create the concatenated String and then take its
length? That is likely more resource intensive than the original
approach to sum length values. So rather do
puts "You have #{first.length + middle.length + last.length} letters
in your name"
or
printf "You have %d letters in your name\n", first.length +
middle.length + last.length
or, if one wants to stay closer at the original solution:
puts 'You have ' + (first.length + middle.length + last.length).to_s
Btw., all the #to_i invocations are superfluous since #length does
return a Fixnum already.