Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 281 Vote(s) - 3.68 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Get immediate subdirectories in ruby

#1
I'm trying to write a simple ruby script that will copy a file to the immediate subdirectories of a directory. How would I get only the immediate subdirectories?
Reply

#2
Based on @glenra's answer but without changing the directory permanently (which may cause issues with `pry`):

```
def folders
Dir.chdir("/some/path/you/want/to/check/below") {
Dir["*"].reject{|o| not File.directory?(o)}
}
end

puts folders # ["all", "the", "folders"]
binding.pry # yay, works

```
Reply

#3
Probably the best way of dealing with files in Ruby is [`Pathname`][1]. It combines class methods from a few file-based modules into one nice-to-use OOP class. So you don't need to pass the value into a method like you'd have to with `Dir` or `File`, you can just call the method on the object itself.

Here's how to print immediate subdirectories:

require 'pathname'

puts Pathname('some/directory').children.select(&:directory?)


[1]:

[To see links please register here]

Reply

#4
Assuming you only wanted the *immediate* subdirectories, you could use `Dir['*/']` (which combines Micheal Sepcot's and glenra's answers).
Reply

#5
If you mean to find all the *immediate* subdirectories (just one level below where you are), try this:

Dir.chdir("/some/path/you/want/to/check/below")
subdir_list=Dir["*"].reject{|o| not File.directory?(o)}

That is: change directory someplace, construct an array of files found there, reject those array elements that aren't directories, and return the resulting culled arrray.
Reply

#6
`Dir.glob("**/")` will return an array of all paths underneath the current directory. From there you can filter the list and copy a file with `File.copy(from, to)`
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through