2016-09-09 102 views
-1

我有这些数据与我:排序JSON数据

[{:id=>250, 
     :application_date=>"02/04/2016", 
     :customer_number=>"", 
     :customer_name=>"Neymar Silva Junior", 
     :city=>"Auckland", 
     :region=>"Auckland", 
     :service=>"Electricity", 
     :name=>"Bosco and Sons", 
     :service_plan=>"Electricity Plan", 
     :connection_type=>nil, 
     :billing_method=>nil, 
     :icp_number=>nil, 
     :moving_date=>"", 
     :supplier_commission=>21.0, 
     :show_url=>"/applications/250"}, 
{:id=>257, 
     :application_date=>"27/05/2016", 
     :customer_number=>"", 
     :customer_name=>"Ariel name Parra", 
     :city=>"Dunedin", 
     :region=>"Dunedin", 
     :service=>"Electricity", 
     :name=>"Bosco and Sons", 
     :service_plan=>"Electricity Plan", 
     :connection_type=>nil, 
     :billing_method=>nil, 
     :icp_number=>nil, 
     :moving_date=>"28/05/2016", 
     :supplier_commission=>21.0, 
     :show_url=>"/applications/257"}, 
{:id=>291, 
     :application_date=>"29/04/2016", 
     :customer_number=>"aaaa", 
     :customer_name=>"Neymar Silva Junior", 
     :city=>"Auckland", 
     :region=>"Auckland", 
     :service=>"Electricity", 
     :name=>"Bosco and Sons", 
     :service_plan=>"Electricity Plan", 
     :connection_type=>nil, 
     :billing_method=>nil, 
     :icp_number=>"", 
     :moving_date=>"", 
     :supplier_commission=>28.0, 
     :show_url=>"/applications/291"}, 
{:id=>292, 
     :application_date=>"29/04/2016", 
     :customer_number=>"23223", 
     :customer_name=>"Neymar Silva Junior", 
     :city=>"Auckland", 
     :region=>"Auckland", 
     :service=>"Electricity", 
     :name=>"Bosco and Sons", 
     :service_plan=>"Electricity Plan", 
     :connection_type=>nil, 
     :billing_method=>nil, 
     :icp_number=>"", 
     :moving_date=>"", 
     :supplier_commission=>21.0, 
     :show_url=>"/applications/292"}] 

我想排序两种不同的方式这个数据,按字母顺序(从A到Z),以及递归(Z到A)根据其在以下情况下属性:

  1. 如果排序参数是service_plan字母顺序它将如果递归则Z排序按这个属性从A到Z,所述的用于该属性等所有属性。

  2. Id是整数,因此应该按照递增或递减顺序排序。

  3. 此外,零值不应该通过一个错误,应该在结果中存在。

在此先感谢!

回答

1
def my_sort(data, attribute, asc = true) 
    # Make sure that all elements have attribute we want the data to be sorted by 
    return data unless data.all? { |elem| elem.key?(attribute) } 

    sorted = data.sort_by { |elem| elem[attribute] } 
    asc ? sorted : sorted.reverse 
end 

my_sort(data, :id) # ascending order by default 
my_sort(data, :city, false) 

如果您想通过元素进行排序,可以丢失:

def my_sort(data, attribute, asc = true) 
    # Convert to string because of possible nil values  
    sorted = data.sort_by { |elem| elem[attribute].to_s } 
    asc ? sorted : sorted.reverse 
end