可对元素为Hash型的数组排序的Ruby Gem: sort_collections
sort_collections:https://github.com/lanrion/sort_collections
?
这个gem的目的是,当我们通过API接收数据的时候(没有使用ActiveRecord),会出现需要对当前数组进行排序,Ruby中已经提供了sort方法,但是该方法,只是对简单的String、Integer等类型排序,如果是Hash呢?我需要针对Hash里的某个key进行排序呢? 这个?sort_collections:https://github.com/lanrion/sort_collections 就是解决这个问题的。
?
安装
gem 'sort_collections'
?
使用举例
?
# init sort datahash_array = [{"created_at"=>"Fri, 31 May 2013 00:26:53 HKT +08:00", "email"=>"peop@example.edu", "updated_at"=>"Fri, 31 May 2013 00:27:21 HKT +08:00"}, {"created_at"=>"Thu, 30 May 2013 18:53:12 HKT +08:00", "email"=>"coco@example.com", "updated_at"=>"Sat, 06 Jul 2013 17:25:13 HKT +08:00"}, {"created_at"=>"Sun, 16 Jun 2013 11:23:42 HKT +08:00", "email"=>"lele@example.com", "updated_at"=>"Tue, 23 Jul 2013 15:44:46 HKT +08:00"}, {"created_at"=>"Fri, 31 May 2013 11:05:24 HKT +08:00", "email"=>"bebe@example.com", "updated_at"=>"Tue, 06 Aug 2013 13:19:09 HKT +08:00"}, {"created_at"=>"Fri, 31 May 2013 11:05:24 HKT +08:00", "email"=>"bebe@example.com", "updated_at"=>"Tue, 06 Aug 2013 13:19:09 HKT +08:00"}, {"created_at"=>"Thu, 30 May 2013 11:19:11 HKT +08:00", "email"=>"admin@example.com", "updated_at"=>"Wed, 11 Sep 2013 15:13:25 HKT +08:00"}]# default: order_type: "asc", order_with: "id"hash_array.order_collection# assign order_with, e.g.: "email"hash_array.order_collection(order_with: "email")# ==> Result:[{"created_at"=>"Thu, 30 May 2013 11:19:11 HKT +08:00", "email"=>"admin@example.com", "updated_at"=>"Wed, 11 Sep 2013 15:13:25 HKT +08:00"}, {"created_at"=>"Fri, 31 May 2013 11:05:24 HKT +08:00", "email"=>"bebe@example.com", "updated_at"=>"Tue, 06 Aug 2013 13:19:09 HKT +08:00"}, {"created_at"=>"Fri, 31 May 2013 11:05:24 HKT +08:00", "email"=>"bebe@example.com", "updated_at"=>"Tue, 06 Aug 2013 13:19:09 HKT +08:00"}, {"created_at"=>"Thu, 30 May 2013 18:53:12 HKT +08:00", "email"=>"coco@example.com", "updated_at"=>"Sat, 06 Jul 2013 17:25:13 HKT +08:00"}, {"created_at"=>"Sun, 16 Jun 2013 11:23:42 HKT +08:00", "email"=>"lele@example.com", "updated_at"=>"Tue, 23 Jul 2013 15:44:46 HKT +08:00"}, {"created_at"=>"Fri, 31 May 2013 00:26:53 HKT +08:00", "email"=>"peop@example.edu", "updated_at"=>"Fri, 31 May 2013 00:27:21 HKT +08:00"}]
?
这样子就非常方便。