Ruby on rails 如何根据散列中的值按函数对散列进行排序

Ruby on rails 如何根据散列中的值按函数对散列进行排序,ruby-on-rails,ruby,sorting,hash,Ruby On Rails,Ruby,Sorting,Hash,我想按以下条件对哈希进行排序: 哈希值为false的对象位于哈希值为true的对象之前。 如果两个对象的hash[:sell]为false,请在此处输入代码,然后计算两个hash的两个变量distance_a,distance_b。如果距离a

我想按以下条件对哈希进行排序:

哈希值为false的对象位于哈希值为true的对象之前。 如果两个对象的hash[:sell]为false,请在此处输入代码,然后计算两个hash的两个变量distance_a,distance_b。如果距离a<距离b,我希望物体a在物体b之前。 代码:


这必须为您做好工作:

def distance(hash)
  LocationDistance.find_by(loc_a: hash[1][:loc_id], current_loc_id].min,
                           loc_b: [hash[1][:loc_id], current_loc_id].max,
                           city_id: current_city.id).distance
end

a.sort{|a,b| a[:sold] == b[:sold] ? ((distance(a) < distance(b)) ? -1 : 1) : (a[:sold] ? 1 : -1)}
借用@Maxim的距离函数并使用sort_,即每个项目只计算一次距离

将距离提取为函数还有一个优点,即它可以独立测试

def distance(hash)
  LocationDistance.find_by(loc_a: hash[1][:loc_id], current_loc_id].min,
                           loc_b: [hash[1][:loc_id], current_loc_id].max,
                           city_id: current_city.id).distance
end

a.sort_by(|x| [true ? 1 : 0, distance(x)])

不清楚您遇到的问题,并且问题的格式不正确。距离a和距离b是从哈希中获得的loc_id的函数。我想使用这两个值对散列进行排序
def distance(hash)
  LocationDistance.find_by(loc_a: hash[1][:loc_id], current_loc_id].min,
                           loc_b: [hash[1][:loc_id], current_loc_id].max,
                           city_id: current_city.id).distance
end

a.sort_by(|x| [true ? 1 : 0, distance(x)])