我想计算数组中的真实对象.因为我可以通过一个块来计算,我找到的最惯用的方式是:
[1, nil, 'foo', false, true].count { |i| i }
#=> 3
Run Code Online (Sandbox Code Playgroud)
但是我想知道是否有更好的方法,特别是使用语法count(&:something),因为在这里传递一个完整的块看起来对我来说太过分了.
AFAIK,truthy?Ruby中没有方法,所以我找不到如何实现这一点.
And*_*eko 13
使用Ruby> = 2.2,您可以使用Object#itself:
[1, nil, 'foo', false, true].count(&:itself)
#=> 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
246 次 |
| 最近记录: |