Read true objects in an array

I would like to read true objects in an array. Since I can pass the block for counting, the most idiomatic way I found was as follows:

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

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

AFAIK, there is no method in Ruby truthy?, so I could not find how to do this.

+4
source share
2 answers

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

[1, nil, 'foo', false, true].count(&:itself)
#=> 3
+12
source

Try the following:

[1, nil, 'foo', false, true].count(true)
-1
source

Source: https://habr.com/ru/post/1657277/


All Articles