在轨道上的红宝石中按字母顺序排序json数据

时间:2016-09-09 14:37:21

标签: ruby-on-rails json ruby sorting

我有这些数据:

[{: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. 如果sort参数按字母顺序排列为service_plan,它将根据此属性从A到Z进行排序,如果是递归,则对该属性按Z到A,依此类推所有属性。

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

  3. 此外,nil值不应该出错,应该出现在结果中。

  4. 提前致谢!

1 个答案:

答案 0 :(得分:2)

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