6

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.

1
  • 2
    Just out of curiosity, one might calculate an amount of falseys [1, nil, 'foo', false, true].count(&:!) and subtract it from original array’s size :) Commented Oct 10, 2016 at 14:04

2 Answers 2

15

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

[1, nil, 'foo', false, true].count(&:itself)
#=> 3
Sign up to request clarification or add additional context in comments.

1 Comment

-1

Try this:

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

1 Comment

This only counts true objects. The goal was to count all truthy objects (ie. 1 and 'foo' should also be counted.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.