Get Names of All Files from a Folder With Ruby

Get names of all files from a folder with Ruby

You also have the shortcut option of

Dir["/path/to/search/*"]

and if you want to find all Ruby files in any folder or sub-folder:

Dir["/path/to/search/**/*.rb"]

Get all file names in a directory with ruby

Dir.new('.').each {|file| puts file }

Note that this will include . and ..

How to get all the filenames of the files inside a folder in Ruby

Use Dir::glob method as below

Dir.glob("#{path}/*.yml").each_with_object({}) do |filename,hsh|
hsh[File.basename(filename,'.yml')] = filename
end

How to get all file names under a folder set into enum in Rails?

From the docs: https://api.rubyonrails.org/classes/ActiveRecord/Enum.html

Declare an enum attribute where the values map to integers in the database.

So if you pass an array (what you do) it'll store the index of the given object not the value.

What you can do is pass in a hash:

assets_path = Rails.root.join('app', 'assets')
assets_files = assets_path.entries.reject(&File.method(:directory?))


enum image: assets_files.map { |img| [img, img] }.to_h

How do I read all the file names of a directory into an array?

You can use this:

files = Dir.foreach(dir).select { |x| File.file?("#{dir}/#{x}") }

This returns the filenames, i.e. without folder.

If you need the complete path, use something like this:

files = Dir.foreach(dir) \
.map { |x| File.expand_path("#{dir}/#{x}") } \
.select { |x| File.file?(x) }

How do I get all the files names in one folder using Ruby?

Break the problem into into parts. The method get_first_part should go something like:

  1. Use Dir to get a listing of files.

  2. Iterate over each file and;

    1. Extract the "name" ('This_is_a_very_good_movie') and the "tag" ('y08iPnx_ktA'). The same regex should be used for each file.

    2. If the "tag" matches what is being looked for, return "name".

Happy coding.


Play around in the REPL and have fun :-)

How to print list of directories and files and exclude names of directories?

Simply check if it's a file.

Dir.glob("**/*").each do |fname|
puts "<file href=\"#{fname}\" />" if File.file?(fname)
end

Get list of subfolders from a given folder in JRuby

please check new stuff it producing expected result -

 records = Dir.glob('/E:/ISSUE_Folder/**/*.*')

records.each do |item|
puts File.dirname(item)
end

enter image description here

As you see its going to every folder and sub folder



Related Topics



Leave a reply



Submit