Home > Mobile >  Ruby read file_name with gets
Ruby read file_name with gets

Time:10-19

I have a beginners coding task, first step is my program "should prompt the user to enter a filename of a file that contains the following information:" There's already pre-made code to work on, a "music_player.rb" (where I have to write the code) and "albums.text" (which is the file I want to read from)

I know a_file = File.new("mydata.txt", "r") is to read from file. I'm trying to do:

file_name = gets()
a_file = File.new("#{file_name}" , "r") # (line 13)

I keep getting error

music_player_with_menu.rb:13:in `initialize': No such file or directory @ rb_sysopen - albums.txt (Errno::ENOENT) 

when I enter albums.txt. If I just remove gets and have File.new("albums.txt" , "r") it works. I'm not sure what I'm doing wrong.

CodePudding user response:

Trying to read from mydata.txt\n is going to raise an exception unless the filename actually ends in \n, which is rarely the case. This is because you're using #gets, which includes the newline character(s) from the user pressing RETURN or ENTER.

When you read from STDIN, you will get a line-ending (e.g. \n on *nix, and \r\n on Windows). So, when you call #gets, you almost always need to call String#chomp on the result.

file_name = gets
#=> "foo\n"

file_name = gets.chomp
#=> "foo"
  • Related