Blackorade
Blackorade

Reputation: 77

What's the difference between gets and readline?

As far as I know, both of them can read from the console. I know gets can read from a file too, but I am interested in console-input.
Example:

a = readline.chomp
puts a
a = gets.chomp
puts a

This gives me the same output. So what's the difference for console-input?

Upvotes: 3

Views: 1016

Answers (1)

undur_gongor
undur_gongor

Reputation: 15954

From ruby-doc.org about Kernel#readline:

Equivalent to Kernel::gets, except readline raises EOFError at end of file.

gets returns nil at end of input.

You can see the difference easily:

echo -n "" | ruby -e "gets"        # no error
echo -n "" | ruby -e "readline"    # -e:1:in `readline': end of file reached (EOFError)

Upvotes: 5

Related Questions