[Ruby] [Ruby] Method to use standard output in conditional branch

less than 1 minute read

When I tried to input standard input using gets like when solving an algorithm problem, I got the following error

$ ruby enc_main.rb new
Traceback (most recent call last):
         2: from enc_main.rb:12:in `<main>'
         1: from enc_main.rb:12:in `gets'
enc_main.rb:12:in `gets': No such file or directory @ rb_sysopen-new (Errno::ENOENT)


It was resolved by using the gets method with $stdin in the code below.

if ARGV[0] == "new"
   puts "What's Name?"
   name = $stdin.gets

Referenced documents

$stdin (Ruby 2.7.0 Reference Manual) Active engineers explain how to use stdin in Ruby [for beginners] | TechAcademy Magazine

Tags: ,