What's the difference between gets.chomp() vs. STDIN.gets.chomp()?

gets will use Kernel#gets, which first tries to read the contents of files passed in through ARGV. If there are no files in ARGV, it will use standard input instead (at which point it's the same as STDIN.gets.

Note: As echristopherson pointed out, Kernel#gets will actually fall back to $stdin, not STDIN. However, unless you assign $stdin to a different input stream, it will be identical to STDIN by default.

http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-gets


gets.chomp() = read ARGV first

STDIN.gets.chomp() = read user's input


If your color.rb file is

first, second, third = ARGV

puts "Your first fav color is: #{first}"
puts "Your second fav color is: #{second}"
puts "Your third fav color is: #{third}"

puts "what is your least fav color?"
least_fav_color = gets.chomp

puts "ok, i get it, you don't like #{least_fav_color} ?"

and you run in the terminal

$ ruby color.rb blue yellow green

it will throw an error (no such file error)

now replace 'gets.chomp' by 'stdin.gets.chomp' on the line below

least_fav_color = $stdin.gets.chomp

and run in the terminal the following command

$ ruby color.rb blue yellow green

then your program runs!!

Basically once you've started calling ARGV from the get go (as ARGV is designed to) gets.chomp can't do its job properly anymore. Time to bring in the big artillery: $stdin.gets.chomp

Tags:

Ruby