【问题标题】:String can't be coerced into Fixnum? [closed]字符串不能被强制转换为 Fixnum? [关闭]
【发布时间】:2013-12-24 05:02:09
【问题描述】:

我正在尝试“99 瓶”计划。我试图简化它,但我得到“字符串不能被强制转换为 Fixnum”:

num_at_start = 99
num_now = num_at_start         
bobo = " bottles of beer on the wall"
bob = " bottles of beer!"
while num_now > 2
  puts num_now.to_s + bobo.to_s    
  puts num_now.to_s + bob.to_s
  puts num_at_start.to_i - 1 + bobo.to_s
  gets
end

【问题讨论】:

  • 您需要在循环中的某处实际减少 num_now。否则它会比实际的歌曲更烦人。
  • 哪一行返回错误?而且,为什么你使用gets 而不存储结果?

标签: ruby fixnum


【解决方案1】:

问题出在这里:

puts num_at_start.to_i - 1 + bobo.to_s

当 args 进入解释器时,Ruby 从左到右建议结果表达式的类型。在这里,您尝试将两个整数相加,使结果为整数。 Fixnum#+ 需要 Fixnum 的实例作为操作数,但出现了 bobo.to_s,即 String

你应该在这里使用inplace eval:

puts "#{num_at_start - 1}#{bobo}"

整个while循环实际上应该写成:

while num_now > 2
  puts "#{num_now}#{bobo}"

  puts "#{num_now}#{bob}"
  puts "#{num_at_start - 1}#{bobo}"
  gets
end

顺便说一句,还有另一个问题:无限循环;但是在您获得现在可以工作的代码后,由您来修复此错误。

【讨论】:

    【解决方案2】:

    这是我编写代码的方式:

    BOBO = '%d bottles of beer on the wall'
    BOB = '%d bottles of beer!'
    
    num_at_start = 2
    while num_at_start > 0
      bobo_str ||= BOBO % num_at_start
      puts bobo_str
      puts BOB % num_at_start
      puts 'Take one down and pass it around'
      num_at_start -= 1
    
      bobo_str = BOBO % num_at_start
      puts bobo_str
      puts
    end
    

    哪些输出:

    # >> 2 bottles of beer on the wall
    # >> 2 bottles of beer!
    # >> Take one down and pass it around
    # >> 1 bottles of beer on the wall
    # >> 
    # >> 1 bottles of beer on the wall
    # >> 1 bottles of beer!
    # >> Take one down and pass it around
    # >> 0 bottles of beer on the wall
    # >> 
    

    我做了一些不同的事情:

    • BOBOBOB 现在是字符串格式。有关说明,请参阅 String#%Kernel#sprintf 文档。
    • num_now = num_at_start 没有意义。只需使用num_at_start
    • 循环测试需要在值大于零时触发,因此编写条件来反映这一点。否则会混淆您和以后处理您的代码的其他人。
    • bobo_str ||= BOBO % num_at_start 是初始化 bobo_str 的简写方式(如果尚未设置)。 ||= 基本上是“赋值,除非它被设置”。

    我建议不要使用while 循环,而是使用Ruby 的downto

    2.downto(1) do |num_at_start|
      bobo_str ||= BOBO % num_at_start
      puts bobo_str
      puts BOB % num_at_start
      puts 'Take one down and pass it around'
    
      bobo_str = BOBO % (num_at_start - 1)
      puts bobo_str
      puts
    end
    

    【讨论】:

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