什么地方出了错
你没有添加任何东西。+ 运算符实际上是一种在字符串和数字上表现不同的方法。在您的情况下, realFirstName.to_s 和朋友正在将 Fixnum 对象(可以添加)转换为 String 对象(使用相同的运算符进行连接)。使用#to_i 和#to_s 并没有错,但如果你在错误的时间进行转换,你可能会遇到麻烦。
什么会做对
String#length 将返回字符串中的字符数。由于它返回 Fixnum,并且 Fixnum#+ 方法执行加法,因此如果在转换为字符串之前调用它,它将按照您期望的方式运行。这两个例子应该是等价的。
# Adding the Fixnum objects.
letter_count = realFirstName + realMiddleName + realLastName
puts "Did you know there are #{letter_count} letters in your name?"
# Adding the String lengths.
letter_count = realFirstName.length + realMiddleName.length + realLastName.length
puts "Did you know there are #{letter_count} letters in your name?"
In this example, we add up all the Fixnum objects, then interpolate the result into our string. Note that #{} does an implicit #to_s for you, so you don't have to do it yourself.
An Advanced Ruby Idiom for the Adventurous
Whether or not this is clearer (it probably isn't), you'll probably run across a lot more examples like the following in real-world Ruby code.
puts "Did you know there are %d letters in your name?" %
[firstName, middleName, lastName].map(&:length).reduce(:+)
Ruby can be a brain-bender, but it's fun!