4

I just started learning Ruby and uncertain what is causing the error. I'm using ruby 1.9.3

puts 'What is your favorite number?'
fav = gets 
puts 'interesting though what about' + ( fav.to_i + 1 )

in `+': can't convert Fixnum into String (TypeError)

In my last puts statement, I thought it is a simple combination of a string and calculation. I still do, but just not understanding why this won't work

4

2 回答 2

13

在 Ruby 中,您通常可以使用“字符串插值”而不是将(“连接”)字符串添加到一起

puts "interesting though what about #{fav.to_i + 1}?"
# => interesting though what about 43?

基本上,内部的任何内容#{}都会被评估,转换为字符串,然后插入到包含的字符串中。请注意,这仅适用于双引号字符串。在单引号字符串中,您将得到您输入的内容:

puts 'interesting though what about #{fav.to_i + 1}?'
# => interesting though what about #{fav.to_i + 1}?
于 2012-11-23T10:50:56.163 回答
3

( fav.to_i + 1 ) returns an Integer, and ruby does not do implicit type conversion. You have to convert it yourself by doing ( fav.to_i + 1 ).to_s to be able to add it to the string.

于 2012-11-23T10:10:57.377 回答