Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count truthy objects in an array

Tags:

ruby

I'd like to count truthy objects in an array. Since I can pass a block to count, the most idiomatic way I found was this:

[1, nil, 'foo', false, true].count { |i| i }
#=> 3

But I was wondering if there was a better way, especially using the syntax count(&:something), because passing a full block here looks like overkill to me.

AFAIK, there is no truthy? method in Ruby, so I couldn't find how to achieve this.

like image 367
Mat Avatar asked Dec 14 '22 03:12

Mat


1 Answers

With Ruby >= 2.2 you can use Object#itself:

[1, nil, 'foo', false, true].count(&:itself)
#=> 3
like image 54
Andrey Deineko Avatar answered Jan 02 '23 03:01

Andrey Deineko