Ruby gets/puts only for strings?

时间秒杀一切 提交于 2019-12-17 18:36:59

问题


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!'

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?


回答1:


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!'

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!"



回答2:


Use the to_i method to convert it to an integer. In other words, change this:

num = gets.chomp

To this:

num = gets.chomp.to_i



回答3:


you can also make sure the number that the user is using is an integer this way:

num = Integer(gets.chomp)

but you have to create a way to catch the error in case the user input otherwise like a char, or string so; it is must better to use:

num = gets.chomp.to_i

In case the user put another type of data, num will be equal to 0 like you can see in this test example:

puts "give me a number:"
num = gets.chomp.to_i
if num >3
 puts "#{num} es mayor a 3 "
else 
 puts "#{num} es menor a 3 o 3"
end

This a example of the interaction with that script:

give me a number:
 sggd
0 es menor a 3 o 3
nil

I hope this clarify better your point.




回答4:


I wrote a similar program as yours. Here is how I finally got it to work properly! I had to assign the favorite number to be an integer. Then, in the next line I set the new_fav_num with the value of fav_num +1 and then converted it to string. After that, you can just plug your code into the return statement that you want to say to the user, only you have to convert the first fav_num to a string.

puts "What is your favorite number?"

fav_num = gets.chomp.to_i

new_fav_num = (fav_num + 1).to_s

puts "Your favorite number is " + fav_num.to_s + ". That's not bad, but " +
new_fav_num + " is bigger and better!"

Hope this helps.



来源:https://stackoverflow.com/questions/6005692/ruby-gets-puts-only-for-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!