0

Ruby Beginner. Learning to write to files, in a directory. Wondering how to now read those files from a directory? Assume there's a directory "book_test" with some .txt files, with a line of text in each file.

puts "Enter name:"
name = gets.strip
filename = "#{name}.txt"
puts "Enter number:"
number = gets.strip
number_in_file = "#{number}"

File.write("/Users/realfauxreal/book_test/#{filename}", number_in_file)

so far so good. I can add a bunch of .txt files with some numbers (or whatever) in them, to the "book_test" dir.

Now If I want to retrieve them, obviously this doesn't work.

Dir.open "/Users/realfauxreal/book_test" do |dir|
    dir.each do |name, number|
        puts "#{name}, #{number}"
    end
end

Am I on the right track? Obviously this isn't outputting properly, plus there are some additional files that I don't want to show up. Is this a case for the .glob helper? If I'm way off base, any tips would be appreciated.

realfauxreal
  • 113
  • 7
  • 2
    I highly recommend you first try to google the question you interested in: "ruby work with files" - the first link is pretty helpful in the understanding of how to work files/directories in many ways. This resource to help programmers to solve problems and not to say: "Yes, it's the correct way/No it's not", because such an interpretation of your question I might guess it's opinion based question. it's just a friendly recommendation to avoid downvoting of your questions in the future, hope you will enjoy learning of this awesome language :) – Oleksandr Holubenko Sep 25 '20 at 16:43
  • Does this answer your question? [Get names of all files from a folder with Ruby](https://stackoverflow.com/questions/1755665/get-names-of-all-files-from-a-folder-with-ruby) – ggorlen Dec 07 '22 at 01:03

1 Answers1

0

Using Dir::[], File::basename and File::read

Dir['/Users/realfauxreal/book_test/*.txt'].each do |file_path|
  p "#{File.basename(file_path)}, #{File.read(file_path)}"
end

"foo.txt, 2"
 => ["book_test/foo.txt"]
Oleksandr Holubenko
  • 4,310
  • 2
  • 14
  • 28