查看所有元素是否不为零的最短方法是什么?
有没有更直接的方法来做到这一点?
[1, nil, 2, 'a'].all? {|x| x}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
有没有更直接的方法来做到这一点?
[1, nil, 2, 'a'].all? {|x| x}
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(5)
使用
include?
并在开始:如果所有元素都非 nil,则数组不包含
nil
。使用.all?
意味着您必须扫描整个数组,.include?
应该在找到匹配项后立即停止,并且没有调用块的开销;因此,.include?
应该更快,但性能差异可能非常无关紧要,除非您有一个巨大的数组。我会选择最适合你的一种。Use
include?
and add a "not" to the beginning:If all elements are non-nil then the array does not include
nil
. Using.all?
means that you have to scan the entire array,.include?
should stop as soon as it finds a match and there's no overhead of calling a block; so,.include?
should be quicker but the performance differences will probably be pretty irrelevant unless you have a massive array. I'd go with whichever one reads best for you.另一种可能性是
任何?
或没有?
方法,以及使用nil?
方法:&:foo
语法可以替换以下内容:list.each() {|x| x.foo()}
Another possibility is the
any?
ornone?
methods, and using thenil?
method:The
&:foo
syntax works to replace anything like:list.each() {|x| x.foo()}
你在打高尔夫球吗?
这就是您所能得到的最简短和直接的内容。就我个人而言,我更喜欢一种稍微详细的方式:
Are you playing Golf?
That's about as short and direct as you are gonna get. Personally I'd prefer a slightly more verbose way:
我想你可以这样做::
但我发现这比你原来的代码不太直接。不过,字符较少,如果您不喜欢块,这会将块隐藏在 &: 符号中
[好吧,您的原始代码有一个问题,即 {|x| x } 对于 nil 和 false 值都计算为 false。如果你真的想要块 {|x| !x.nil?} ]
I suppose you could do::
But I find that less direct than your original code. Fewer characters, though, and if you dislike blocks this hides the block in the &:symbol
[Well, your original code has a problem which is that {|x| x } evaluates as false for both nil and false values. If you really want the block {|x| !x.nil?} ]
几乎与 mu 相同,太短了,我不认为我的比它更好,但只是另一种变体:
Almost the same as mu is too short, and I don't think mine any better than it, but just another variant: