← All languages
Ruby method of the day
Random

gets

Read a line of input from standard input.

Description

The gets method reads the next line from standard input (or from the files listed in ARGV). It returns the line as a string including the trailing newline character, or nil if the end of input has been reached.

An optional separator argument specifies the line delimiter. If the separator is nil, the entire remaining input is read. If it is an empty string, gets reads in paragraph mode, returning the next paragraph delimited by two newlines.

This method is commonly used for interactive programs that need user input. The result typically has chomp or strip called on it to remove the trailing newline before processing.

Arguments

NameDescriptionOptional
sep The line separator string. Defaults to the value of $/. Yes
limit Maximum number of bytes to read. Yes

Example

print "Enter your name: "
name = gets.chomp
puts "Hello, #{name}!"

Reference