Muhammad Usman
Muhammad Usman

Reputation: 10936

'.all?' method's strange behaviour

I am unable to understand what all? does. In the following code, the first two lines are the same. Why are the outputs different? Is it a bug or is it its default behaviour?

[false, false, true, true, true, true, false, false, true, true].all? # => false
[true, true, true, true, true, true, true, true, true, true].all? # => true
[0, 0, 1, 1, 1, 1, 0, 0, 1, 1].all? # => true

Upvotes: 0

Views: 83

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118289

Because Enumerable#all? says :

If the block is not given, Ruby adds an implicit block of { |obj| obj } which will cause all? to return true when none of the collection members are false or nil.

In your second line,the code return true as none of the collection members are false or nil

In your third line code returns true ,as all objects in your code collection (0,1) are true,as in Ruby all objects are true except nil and false.

In your first line,the code return false,as the collection contains false values along with true values.

Upvotes: 4

Job
Job

Reputation: 230

This is a ruby method, which is defined as follows:

Passes each element of the collection to the given block. The method returns true if the block never returns false or nil. If the block is not given, Ruby adds an implicit block of { |obj| obj } which will cause all? to return true when none of the collection members are false or nil.

See the documentation here.

Upvotes: 4

Related Questions