Ruby 文件操作 Dir 怎么得到随机文件?

datty258 · December 03, 2013 · Last by datty258 replied at December 03, 2013 · 2568 hits

先得到一个集合 d = Dir.new("/home/下载/头像") 头像文件夹下有很多文件 怎么在 d 中得到随机一个文件?

将头像下的文件名生成一个数组,然后随机选中一个

Dir['/home/下载/头像/**/*'].sample

#1 楼 @showlovel 我也想到了这个办法,看看有人没有知道简单的方法。谢了

#2 楼 @iBachue 这样是不行的。

#5 楼 @iBachue Dir['/home/下载/头像/*/'].sample 返回的是空,Dir['/home/下载/头像/*.jpg'].sample => nil 我对这块不是很了解。

确定目录是否存在:

irb(main):010:0> Dir['/tmp/*'].sample
=> "/tmp/launchd-359.t4qrx5"
irb(main):011:0> Dir['/home/*'].sample
=> nil

2B 行为不断,是我的错误,多谢#5 楼 @iBachue #7 楼 @santochancf

You need to Sign in before reply, if you don't have an account, please Sign up first.