【问题标题】:Ruby puts string and integer on same lineRuby 将字符串和整数放在同一行
【发布时间】:2012-11-11 16:28:48
【问题描述】:

我刚开始学习 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)

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

【问题讨论】:

    标签: ruby-on-rails ruby puts


    【解决方案1】:

    在 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}?
    

    【讨论】:

      【解决方案2】:

      ( fav.to_i + 1 ) 返回一个 Integer,而 ruby​​ 不做隐式类型转换。您必须自己通过 ( fav.to_i + 1 ).to_s 进行转换才能将其添加到字符串中。

      【讨论】:

      • 好吧,是不是有点像字符串配字符串?整数不能与字符串混合?感谢您的解决方案!
      • 是的,有点像:Here's a good read about it。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多