Gets and chomp issue ? (newbie)

Hello folks, i’m learning ruby and i’m trying to keep code running after getting inputs from user how is that ?
this is my code :


  puts '---------please enter database name---------'
  database = gets
  puts '---------hello please enter username---------'
  username = gets

  # Attributes
  database = gets
  username = gets

  connection = PG.connect dbname: database, user: username
  system("pg_dump -h localhost -p 5432 #{database} > backup.sql")
rescue PG::Error => e
  puts e.message

I’m a little confused. Firstly, you are going to need to chomp your user inputs to remove the trailing newline:

database = gets.chomp

but I really don’t understand why you are making the connection to the database, and then shelling out to a pg_dump command that doesn’t use the connection?

i’m trying to backup the database hhh i know it so dump, i’m learning ruby
btw any good practice ?

pg_dump makes its own connection to the database. You don’t need to make another connection in Ruby as well, because it won’t be used.

Just a suggestion :slight_smile:

If you want to read user input from standard input, use STDIN.gets, instead of gets (Kernel.gets).
Kernel.gets actually reads command line arguments and assumes that the argument is a file. Here’s an example (screenshot):

Without argument, 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.

Other Notes:

  • 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), STDIN.gets returns 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 STDIN.gets returns nil, the variable “something” will be nil, and program won’t crash.

1 Like