In this section we will learn what the gets() method is and how to use it in Ruby.
Note: we’re assuming you’re familiar with the Ruby puts method.
What is gets method in Ruby?
The Ruby gets method is used to take an input from a user and return that as a result of calling the method.
Ruby gets Method Syntax:
val = gets
Note that the `val` is actually the variable that is going to hold the inputs that a user has entered.
Ruby gets Method Return Value:
The return value of this method is the input value that a user has entered in a string form. That means even if a user has entered an integer number, still it will be stored as a string type of value. So we need to convert the value into integer if we’re expecting such type of value from users.
Note: in the String methods section, we will explain how to convert a string data type to other forms.
Also note that the return value from the gets method contains the newline character as well. So if you don’t want that, you can use the chomp method which is part of the string methods in order to trim away the newline character.
Example: taking inputs from users using gets method
puts "What's your full name?" full_name = gets full_name = full_name.chomp puts "Hello #{full_name}"
Output:
What's your full name? Omid Dehghan Hello Omid Dehghan
How does gets method work in Ruby?
The full_name variable is the holder of the value that will be returned from the `gets` method. So when we run the program, it will ask the user to put her full name and this value will be stored in the `full_name` variable.
We then used the `chomp` method to remove the newline character from the end of the returned value and finally sent that value to the output stream using `puts “Hello #{full_name}” statement.
Note: in the last statement we’ve used String Interpolation. Please check the related section to learn more about String Interpolation in Ruby.