【问题标题】:String can't be coerced into Fixnum (TypeError)字符串不能被强制转换为 Fixnum (TypeError)
【发布时间】:2014-08-20 05:45:21
【问题描述】:

我写了下面的基本代码

puts ' Hi there , what is your favorite number ? '
number = gets.chomp
puts number + ' is beautiful '
puts 1 + number.to_i + 'is way better'

但是当我运行它时,我收到错误“无法将字符串强制转换为 Fixnum (TypeError)”。请问如何改正这个错误?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    您不能将字符串添加到数字。您可以将数字添加到字符串,因为它被强制转换为字符串:

    '1' + 1
    # => "11"
    1 + 1
    # => 2
    1 + '1'
    # TypeError!
    

    既然我怀疑你想显示数字加 1 的结果,你应该明确地cast it to string

    puts (1 + number.to_i).to_s + ' is way better'
    

    或者,使用string interpolation

    puts "#{1 + number.to_i} is way better"
    

    【讨论】:

      【解决方案2】:

      字符串不能被强制转换为整数通常发生在您尝试将字符串添加到数字时。因为您想将 1 添加到您的号码并将其与字符串“更好”连接起来。你必须明确地将你的数字加 1 得到的结果转换为一个字符串,并将它与你的字符串连接起来“更好”。

      您可以将代码更新为:

      puts (1 + number.to_i).to_s + " " + 'is way better'
      

      【讨论】:

        【解决方案3】:

        假设数字是自然数:

        number = gets.chomp
        puts "#{number} is beautiful ", "#{number.succ} is way better"
        

        【讨论】:

        • 虽然 succ 不理解负数
        【解决方案4】:

        您可能会发现输入“xyz”作为输入的结果令人惊讶。

        discussion 用于确定您的输入字符串是否为数字可能会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-22
          相关资源
          最近更新 更多