我是编程的新手,我正在尝试回答这个基本问题。
编写一个程序,询问一个人最喜欢的号码。让您的程序在数字中添加一个,然后将结果建议为更大,更好的数字。
这就是我所要做的,但它不会转换为数字。
puts "What is your favorite number?"
number = gets.chomp
number = number.to_i + 1
puts "I suggest " + number + " as a bigger and better number"
答案 0 :(得分:11)
仔细查看您得到的错误:
What is your favorite number?
42
number.rb:4:in `+': can't convert Fixnum into String (TypeError)
from number.rb:4:in `<main>'
第4行是:
puts "I suggest " + number + " as a bigger and better number"
问题是Ruby不会将number
隐式转换为字符串(例如"foo" + 42
在Ruby中无效)。有几种解决方案:
在to_s
上调用number
,在连接之前将其转换为字符串:
puts "I suggest " + number.to_s + " as a bigger and better number"
puts "I suggest #{number} as a bigger and better number"
选项2更惯用,我建议使用它。
答案 1 :(得分:4)
正如ruby中的许多其他问题一样,有很多方法可以做到这一点....如果没有上面提到的三个解决方案,还有两个:
puts "What is your favorite number?"
number = gets.chomp.to_i
puts "I suggest %d as a bigger and better number" % [number + 1]
和一个几乎相同:
puts "What is your favorite number?"
number = gets.chomp.to_i
num = number + 1
puts "I suggest %d as a bigger and better number" % [num]
答案 2 :(得分:1)
你可以这样做:
print 'What is your favorite number? '
number = gets.chomp
puts "I suggest #{number.to_i + 1} as a bigger and better number"
关于代码的解释并不多,但有几点需要考虑:
'text'
而不是"text"
。 “在双引号的情况下,Ruby做了更多工作。首先,它寻找替换(序列
以反斜杠字符开头)并用一些二进制值替换它们“ - Programming ruby 1.9.3 这里的东西真的很微不足道,但是当你编写大型程序,网页等时,它确实有所作为。