开发者

Ruby gets/puts only for strings?

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 ba开发者_运维百科d 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?


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


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜