Iterate through every file in one directory

前端 未结 8 2047
忘了有多久
忘了有多久 2020-11-30 16:52

How do I write a loop in ruby so that I can execute a block of code on each file?

I\'m new to ruby, and I\'ve concluded that the way to do this is a do each loop.

8条回答
  •  执念已碎
    2020-11-30 17:20

    This is my favorite method for being easy to read:

    Dir.glob("*/*.txt") do |my_text_file|
      puts "working on: #{my_text_file}..."
    end
    

    And you can even extend this to work on all files in subdirs:

    Dir.glob("**/*.txt") do |my_text_file| # note one extra "*"
      puts "working on: #{my_text_file}..."
    end
    

提交回复
热议问题