Signup/Sign In

Getting Data from User using gets in Ruby

To make the program to interact with user, a program usually needs input from the users. To do this, we can use gets method. gets function takes input from the keyboard in string format and stores the value in the variables.

name = gets

This statement takes a string input from the user and stores it in the variable called name.

It also appends a \n new line character at the end of the input entered by the user.

gets method to get user data in ruby

So, when you type the variable name, it displays what is stored in it. When you display using print function, it displays the text entered by the user along with a new line. To remove the newline, you can use a function called chomp. The following statement removes the newline from the input entered by the user.

print name.chomp

The following code performs addition of two whole numbers with the numbers provided by the user:

number1 = gets
number2 = gets
(Integer)number1 + Integer(number2)

Integer() part of the code looks tricky for you now.

As mentioned before, gets method gets input in string format. So, conversion to whole number is required before arithmatic operations could be perfomed on the data. This can be done using Integer() function.

If you don't convert those variables into integer, it will concatenate the two string instead of performing arithmatic addition,. Do you remember concatenating two strings which we have seen earlier in Chapter 1? Likewise, to add two decimal numbers, look at the following code:

num1 = gets
num2 = gets
float(num1) + float(num2)

NOTE: float() method is used to convert data into decimal format. If the conversion is not done, it simply performs the concatenation operation as said before.