【问题标题】:Where do I call '.to_i' in this code?在这段代码中我在哪里调用“.to_i”?
【发布时间】:2014-12-28 13:31:33
【问题描述】:

我正在学习 Chris Pine 的Learn to Program,但我无法让这个练习发挥作用。 从用户那里得到一个num,然后应该告诉用户num + 1是一个更大更好的数字。

使用此代码: 1 puts 'What\'s your favorite number?' 2 num = gets.chomp 3 num = num.to_i + 1 4 puts num +' is a bigger and better favorite number.'

我在第 4 行收到此错误: in '+': String can't be coerced into Fixnum (TypeError)

所以我的字符串变量实际上并没有被转换为整数,对吧?我该如何完成这项工作?

【问题讨论】:

    标签: ruby string methods


    【解决方案1】:

    在最后一行,代码试图将数字与字符串连接起来。

    >> 1 + ' is ...'
    TypeError: String can't be coerced into Fixnum
            from (irb):2:in `+'
            from (irb):2
            from C:/Ruby21-x64/bin/irb:11:in `<main>'
    

    在连接之前将数字转换为字符串。 + 和 '...' 之间应该有空格

    puts num.to_s + ' is a bigger and better favorite number.'
                   ^
    

    或者使用字符串插值:

    puts "#{num} is a bigger and better favorite number."
    

    【讨论】:

    • 再次感谢! Stack Overflow 非常有帮助,但我显然仍在学习中。 :)
    【解决方案2】:

    将此作为最后一行 -

    puts "#{num} is a bigger and better favorite number."
    

    【讨论】: