Ruby/在sort_by中为nil时避免错误 [英] Ruby / avoid errors when nil in sort_by

查看:148
本文介绍了Ruby/在sort_by中为nil时避免错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自这个问题(@mudasobwa);

From this question (@mudasobwa);

input.sort_by { |h| sorter.index(h[:id]) }

在某些不幸的情况下; sorter.index(h [:id])返回nil,然后返回错误

In some unfortunate cases; sorter.index(h[:id]) returns nil, it then returns an error

在对其余数组进行排序的同时,如何干净地避免发生此类错误?

How would one cleanly avoid such error to happen, while having the rest of the array sorted ?

推荐答案

input.sort_by { |h| [sorter.index(h[:id]) ? 1 : 0, sorter.index(h[:id])] }

这将获取所有值,根据它们是否最初具有sorter.index(h [:id])进行排序,然后按该值对该值进行排序

This will take all values, sort them by whether they have a sorter.index(h[:id]) available initially, and then sort those with that value by that value

这篇关于Ruby/在sort_by中为nil时避免错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆