ruby sort_by multiple fields

后端 未结 1 1605
暖寄归人
暖寄归人 2021-02-11 16:35

I\'m running 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.ba         


        
1条回答
  •  难免孤独
    2021-02-11 17:21

    Your sorting works correctly in MRI Ruby 1.8.7, 1.9.3, and 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]}
    # => [#,
    #     #,
    #     #,
    #     #,
    #     #,
    #     #]
    

    Have you tried outputting the result of your sort_by to a console? I'm not familiar with the render json: portion of your code, but perhaps that's where things are going wrong. My best guess is that somehow in the conversion to JSON (if that's what it does) the sorting is getting messed up.

    My other idea is that perhaps you expect sort_by to modify entries; it does not. If you want entries itself to be sorted after the call, use sort_by! (note the ! at the end of the method name).

    Update: It looks like the issue is that you want a case-insensitive search. Simply adding upcase should do the trick:

    entries.sort_by{|e| [e.sort_dir, e.name.upcase]}
    

    0 讨论(0)
提交回复
热议问题