Ruby只为字符串获取/放置? [英] Ruby gets/puts only for strings?
问题描述
我是Ruby新手,我目前正在研究一些类似于以下内容的练习代码:
I'm new to Ruby and am currently working on some practice code which looks like the following:
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'变量设为整数?我没有成功,所以有人能告诉我哪里出错吗?
This code however just puts ten copies of the num variable and doesn't actually multiply the number so I assume I need to make the 'num' variable an integer? I've had no success with this so can anyone show me where I'm going wrong please?
推荐答案
如果您正在使用 to_i
,然后 chomp
,然后才是多余的。所以你可以这样做:
If you are using to_i
, then chomp
before that is redundant. So you can do:
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#+
特别慢。
But generally, using "#{}"
is better since you do not have to care about to_s
, and it runs faster, and is easier to see. The method String#+
is particularly very slow.
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!"
这篇关于Ruby只为字符串获取/放置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!