Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby gets/puts only for strings?

Tags:

integer

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

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?

like image 748
AndyNico Avatar asked May 15 '11 00:05

AndyNico


People also ask

Why does Ruby use puts?

By default, Ruby doesn't display any output. The methods puts and print are a great way to explicitly tell the program to display specific information. Without these printing methods, Ruby will read the line, but not print anything out.

Why we use gets chomp in Ruby?

chomp! is a String class method in Ruby which is used to returns new String with the given record separator removed from the end of str (if present). chomp method will also removes carriage return characters (that is it will remove \n, \r, and \r\n) if $/ has not been changed from the default Ruby record separator, t.

How do you use gets in Ruby?

gets must return an object, so you can call a method on it, right? If so, lets name that object returned by gets as tmp , then you can call the chomp method of tmp . But before gets returns tmp , it should print a new line on the screen.

How do you convert string to int in Ruby?

To convert an string to a integer, we can use the built-in to_i method in Ruby. The to_i method takes the string as a argument and converts it to number, if a given string is not valid number then it returns 0.


1 Answers

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!"
like image 72
sawa Avatar answered Nov 16 '22 00:11

sawa