2016-09-09 135 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