将字符串数字添加到ruby中

时间:2015-07-26 12:49:18

标签: ruby string integer gets puts

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

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。 我无法将长度转换为整数,因为我之前无法添加文本字符串。

1 个答案:

答案 0 :(得分:-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?'