DEV Community

Andressa
Andressa

Posted on

Receiving input from user in Ruby

How gets actually work under the hood

It uses the $stdin global variable. It represents the current standard input.

The method gets, communicates with the input stream on your computer ( which is connected to your Operating System ) receiving data from the $stdin global variable and assigning it to your variable while returning the value stored with a new line char appended at the end.

irb(main):005:0> name = gets
andressa
=> "andressa\n"    
Enter fullscreen mode Exit fullscreen mode

we can get rid of the new line char by calling the chomp method.

irb(main):006:0> name = gets.chomp
andressa
=> "andressa"  
Enter fullscreen mode Exit fullscreen mode

If dealing with files, it returns nil when reaching the end of the file.

gets receives input in a string format, so if you are expecting to deal with integers, for example, you will need to convert it to an int first.

irb(main):009:0> number = gets.chomp
34
=> "34"                                                                         
irb(main):010:0> number.class
=> String
Enter fullscreen mode Exit fullscreen mode

Top comments (0)