Just a suggestion
If you want to read user input from standard input, use
STDIN.gets, instead of gets (
Kernel.gets actually reads command line arguments and assumes that the argument is a file. Here’s an example (screenshot):
gets behaves like
STDIN.gets, with arguments it reads the file with argument (
ARGF) and then shifts it. If you put another gets, it will read the next argument as file.
In my case you see I didn’t have the 1234 file, so my program crashes. But after creating the file, it didn’t. If 1234 has some contents,
gets will return that.
So my suggestion is to use
STDIN.gets. Otherwise, don’t be upset if your program crashes.
Also note that to make it robust use
STDIN.gets.to_s because some non TTY terminals (like terminal in atom text editor or visual studio editor),
nil… to_s won’t make your program consume more memory if your STDIN.gets has something, but it will return empty string (new object) if
STDIN.gets returns nil.
You can also use
something = STDIN.gets &.chomp. In this case, if
nil, the variable “something” will be nil, and program won’t crash.