Richlewis Richlewis - 3 months ago 16
Ruby Question

excluding directory names - ruby

I have the inherited the following that gets me all the folders that i require

folders = Dir.entries('features/tmp').select { |entry| File.directory? File.join('features/tmp', entry) and !(entry == '.' || entry == '..' || entry == '.git' || entry == 'step_definitions') }


But I am looking to refactor this to clean it up and to add something easier if i ever wanted to exclude any folders in the future rather than chaining the query

So I have come up with this but get the following error

# Dir.entries('features/tmp').select { |entry| p entry }
# [".", "..", ".git", "idv4", "step_definitions"]

exclude = %w(. .. .git step_definitions)
Dir.entries('features/tmp').select { |entry| File.directory? File.join('features/tmp', exclude.include?(!entry))}

TypeError: no implicit conversion of false into String
from (pry):26:in `join'


Have i approached this wrong or am i missing something obvious? I basically want to get all the folder names that are not in the exclude array

Thanks

Answer

You had the conditions a bit mixed up - note the order of operations. I added the parentheses to the File.directory? call to make it clearer.

exclude = %w(. .. .git step_definitions)
Dir.entries('features/tmp').select { |entry|
    File.directory?(File.join('features/tmp', entry)) && \
    !exclude.include?(entry)
}
  1. File.join just joins multiple strings using the system's path separator. So joining the parent directory name with a boolean (exclude.include(!entry)) isn't what you were trying to do I hope, but rather check if that file is a directory - so the join should remain the same as before
  2. exclude.include(!entry) is another problem because you're trying to negate a string. !'string' == false. You need to check if the whole inclusion part is false - so move the ! to the beginning of that expression.