Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 58 / 68

Reading from Standard Input

In this lesson you will learn to read from standard input with gets so you can build interactive command-line tools. This is for anyone searching for "Ruby gets how to use".

gets reads one line of input from the keyboard or another source. Pairing it with chomp to strip the trailing newline is the standard form.

The sample code prints a prompt and then reads the input with gets.chomp. Chaining .chomp straight onto what gets returns keeps it concise.

A common stumbling block for beginners is using gets without chomp. The string it returns still carries a trailing newline, and without removing it your later comparisons and output can behave unexpectedly.

Using strip instead of chomp removes leading whitespace as well as trailing. Using input without validating it can lead to unexpected errors, so pairing it with a validation step is safer.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)