0

我制作了这个程序,它计算你名字中的字符。

puts 'What is your first name?'
forename = gets.chomp
puts 'what is your middle name?'
middlename = gets.chomp
puts 'what is your surname?'
surname = gets.chomp
puts 'Did you know there are ' + forename.length.to_s + middlename.length.to_s + surname.length.to_s + ' characters in your name?'

但是,这将彼此相邻的数字相加等于 555 而不是 15。我无法将长度转换为整数,因为我之前无法添加文本字符串。

4

1 回答 1

-1
puts 'What is your first name?'
forename = gets.chomp
puts 'what is your middle name?'
middlename = gets.chomp
puts 'what is your surname?'
surname = gets.chomp
name_length = [forename,middlename,surname].map(&:length).inject(:+)
puts 'Did you know there are ' + name_length + ' characters in your name?'

或者只是没有#to_s。使用#to_s,您可以将数字转换回字符串并连接字符串。

puts 'What is your first name?'
forename = gets.chomp
puts 'what is your middle name?'
middlename = gets.chomp
puts 'what is your surname?'
surname = gets.chomp
puts 'Did you know there are ' + forename.length + middlename.length + surname.length + ' characters in your name?'
于 2015-07-26T12:54:33.677 回答