Ruby将字符串和整数放在同一行

cat*_*key 3 ruby ruby-on-rails puts

我刚开始学习Ruby并且不确定导致错误的原因.我正在使用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)
Run Code Online (Sandbox Code Playgroud)

在我上一篇put语句中,我认为它是字符串和计算的简单组合.我仍然这样做,但只是不明白为什么这不起作用

And*_*nes 10

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

puts "interesting though what about #{fav.to_i + 1}?"
# => interesting though what about 43?
Run Code Online (Sandbox Code Playgroud)

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

puts 'interesting though what about #{fav.to_i + 1}?'
# => interesting though what about #{fav.to_i + 1}?
Run Code Online (Sandbox Code Playgroud)