我正在运行Ruby 1.9.3p392。
Item = Struct.new( :name, :dir, :sort_dir )
entries = ftp.list()
entries.map!{|e| Net::FTP::List.parse(e) }.map!{|e| Item.new( e.basename, e.dir?, (e.dir? ? 0 : 1) ) }
render json: entries.sort_by{ |e| [ e.sort_dir, e.name ]}
出于某种原因,我没有按预期得到结果。
我确实先获取所有文件夹,然后是所有文件,但名称排序失败。
例如,我为我的文件夹获取了这些文件:
对于文件:
它将目录/文件部分分组正确,但名称排序不正确。
排序后,控制台的输出如下所示:
#<struct FtpController::Item name="Content", dir=true, sort_dir=0>
#<struct FtpController::Item name="Images", dir=true, sort_dir=0>
#<struct FtpController::Item name="Scripts", dir=true, sort_dir=0>
#<struct FtpController::Item name="Views", dir=true, sort_dir=0>
#<struct FtpController::Item name="bin", dir=true, sort_dir=0>
#<struct FtpController::Item name="Global.asax", dir=false, sort_dir=1>
#<struct FtpController::Item name="Web.config", dir=false, sort_dir=1>
#<struct FtpController::Item name="favicon.ico", dir=false, sort_dir=1>
#<struct FtpController::Item name="packages.config", dir=false, sort_dir=1>
#<struct FtpController::Item name="robots.txt", dir=false, sort_dir=1>
答案 0 :(得分:59)
您的分类在MRI Ruby 1.8.7,1.9.3和2.0.0中正常工作:
Item = Struct.new(:name, :dir, :sort_dir)
entries = [Item.new('favicon.ico', false, 1), Item.new('bin', true, 0),
Item.new('web.config', false, 1), Item.new('images', true, 0),
Item.new('global.asax', false, 1), Item.new('content', true, 0)]
entries.sort_by{|e| [e.sort_dir, e.name]}
# => [#<struct Item name="bin", dir=true, sort_dir=0>,
# #<struct Item name="content", dir=true, sort_dir=0>,
# #<struct Item name="images", dir=true, sort_dir=0>,
# #<struct Item name="favicon.ico", dir=false, sort_dir=1>,
# #<struct Item name="global.asax", dir=false, sort_dir=1>,
# #<struct Item name="web.config", dir=false, sort_dir=1>]
您是否尝试将sort_by
的结果输出到控制台?我不熟悉代码的render json:
部分,但也许这就是出错的地方。我最好的猜测是,不知何故,在转换为JSON(如果这就是它的作用)时,排序变得混乱。
我的另一个想法是,您希望sort_by
修改entries
;它不是。如果您希望在通话后对entries
本身进行排序,请使用sort_by!
(请注意方法名称末尾的!
)。
更新:看起来问题是你想要一个不区分大小写的搜索。只需添加upcase
即可:
entries.sort_by{|e| [e.sort_dir, e.name.upcase]}