【问题标题】:ruby code error: '+'no implicit conversion of Integer into String红宝石代码错误:'+'没有将整数隐式转换为字符串
【发布时间】:2019-06-10 17:25:53
【问题描述】:

获取运行时代码错误:在“+”中:没有将 Integer 隐式转换为 String TypeError

num = 5;
puts ("this is number: " + num);

实际结果:

运行时代码错误:在“+”中:没有将 Integer 隐式转换为 String TypeError

预期结果 - 我应该看到打印的声明 -

这是数字:5

【问题讨论】:

  • 包含变量的推荐方法是使用字符串插值:"this is number: #{num}"

标签: ruby


【解决方案1】:

首先不要在方法名称和左括号之间放置空格。

错误的原因是无法将数字添加到字符串中,ruby 防止了隐式强制。可能会使用字符串插值:

puts "this is number: #{num}"

或将数字显式转换为字符串:

puts("this is number: " + num.to_s)

旁注:分号在行尾是多余的,应该避免。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 2017-01-19
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多