Ruby list directory with Dir['*'] including dotfiles but not . and

允我心安 提交于 2019-12-09 14:31:07

问题


How do I get Dir['*'] to include dotfiles, e.g., .gitignore, but not . and ..?

I.e., is there a better way to do:

`ls -A`.split "\n"

perhaps with Dir? The following solutions are close but both include . & ..:

Dir.glob('*', File::FNM_DOTMATCH)
Dir['{.*,*}']

So, the following works:

Dir.glob('*', File::FNM_DOTMATCH) - ['.', '..']

But, is there still a better way to do this?

I'm wondering this to fix line 9 of a Meteor Homebrew Formula.


回答1:


You can't with Dir[], but you can with Dir.glob, which Dir[] calls:

Dir.glob("*", File::FNM_DOTMATCH)

You can get rid of the . & .. easily:

Dir.glob("*", File::FNM_DOTMATCH).tap { |a| a.shift(2) }

But I think it’s probably best to stick with your original way:

Dir.glob("*", File::FNM_DOTMATCH) - %w[. ..]

(among other ways)

However, if you don’t require a more sophisticated glob than *, Dir#children may be all you need (can always further filter/grep the results if more filtering is needed):

Dir.children('.')



回答2:


Here's a shorter version:

Dir['{.[^\.]*,*}']



回答3:


The following works with Dir.glob:

Dir.glob("{*,.?*}")


来源:https://stackoverflow.com/questions/11385795/ruby-list-directory-with-dir-including-dotfiles-but-not-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!