有用于返回第一阵列元素,如果只有一个存在一个红宝石成语? [英] Is there a ruby idiom for returning the first array element, if only one exists?

查看:182
本文介绍了有用于返回第一阵列元素,如果只有一个存在一个红宝石成语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回数组的第一个元素,如果阵列只包含一个值。

I would like to return the first element of an array, if the array only contains one value.

目前,我使用的:

vals.one? ? vals.first : vals.presence

因此​​:

vals = []; vals.one? ? vals.first : vals.presence
# => nil

vals = [2]; vals.one? ? vals.first : vals.presence
# => 2

vals = [2, 'Z']; vals.one? ? vals.first : vals.presence
# => [2, "Z"]

有什么内在的做这个,或者用一个更好的设计考虑是不是?

Is there something inbuilt that does this, or does it with a better design consideration?

我的用例是具体的,涉及presenters那些知道从方法(这将实现上述code)会发生什么。如果这些presenters处理所有的回报作为一个数组,那么在大多数情况下(〜90%),他们将遍历大小的数组 1 0

My use case is specific, involving presenters that know what to expect from the method (which would implement the above code). If those presenters handle all returns as an array, then in most cases (~90%) they will iterate over arrays of size 1 or 0.

推荐答案

您似乎要处理VAL阵列的情况下是未定义所以......

You seem to want to handle the case of val array being undefined so...

val.size > 1 ? val : val[0] if defined?(val)

但正如已经指出的那样倒不如提供一个一致的说法(总是阵列),所以如果不确定下面将提供VAL数组或一个空数组

But as has been pointed out it would be better to deliver a consistent argument (always arrays) so the following will deliver the val array or an empty array if undefined

defined?(val) ? val : []

这篇关于有用于返回第一阵列元素,如果只有一个存在一个红宝石成语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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