我是Ruby的新手,目前正在研究一些如下的练习代码:
puts 'Hello there,Can you tell me your favourite number?' num = gets.chomp puts 'Your favourite number is ' + num + '?' puts 'Well its not bad but ' + num * 10 + ' is literally 10 times better!'
然而,这个代码只是放置了num变量的十个副本,并且实际上并不乘以这个数字,所以我假设我需要使’num’变量为整数.我没有成功,所以任何人都可以告诉我哪里我错了吗?
解决方法
如果你使用to_i,那么之前的chomp是多余的.所以你可以做:
puts 'Hello there,Can you tell me your favourite number?' num = gets.to_i puts 'Your favourite number is ' + num.to_s + '?' puts 'Well its not bad but ' + (num * 10).to_s + ' is literally 10 times better!'
但是一般来说,使用“#{}”更好,因为你不必关心to_s,而且运行速度更快,更容易看到. String#方法特别慢.
puts 'Hello there,Can you tell me your favourite number?' num = gets.to_i puts "Your favourite number is #{num}?" puts "Well its not bad but #{num * 10} is literally 10 times better!"