JackyJohnson
JackyJohnson

Reputation: 3126

check if directory entries are files or directories using ruby

Okay. I'm a big noob at Ruby. What did I miss?

I just want to iterate through a particular folder on OS X and if a sub-entry is a directory I want to do something.

My code:

folder = gets.chomp()
Dir.foreach(folder) do |entry|
  puts entry unless File.directory?(entry)
  # unfortunately directory?
  # doesn't work as expected here because everything evaluates to false, but why?  How is this supposed to be done?
end

Upvotes: 0

Views: 112

Answers (1)

falsetru
falsetru

Reputation: 369094

entry contains only basename part (dirname/basename). You need to join it with folder to get correct path.

folder = gets.chomp()
Dir.foreach(folder) do |entry|
  path = File.join(folder, entry) # <------
  puts entry unless File.directory?(path)
end

In addition to that, you maybe want to skip entry if the entry is . or ...

  next if entry == '.' || entry == '..'

Upvotes: 1

Related Questions