Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby's "any?" and "all?" methods behaviour on Empty Arrays and Hashes

First of all I found two useful articles in documentations about these methods:

  • http://www.ruby-doc.org/core-1.9.3/Enumerable.html
  • http://www.globalnerdy.com/2008/01/29/enumerating-rubys-enumerable-module-part-1-all-and-any/

all?: Passes each element of the collection to the given block. The method returns true if the block never returns false or nil.

any?: Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil.

But in case of empty arrays and hashes I got:

irb(main):004:0> [nil, "car", "bus"].all?
=> false
irb(main):005:0> ["nil", "car", "bus"].all?
=> true
irb(main):006:0> [].all?
=> true
irb(main):007:0> ["nil", "car", "bus"].any?
=> true
irb(main):008:0> [nil, "car", "bus"].any?
=> true
irb(main):009:0> [nil].any?
=> false
irb(main):010:0> [].any?
=> false

Can somebody explain to me why empty arrays give me false in case of the any? method and true in case of all??

like image 721
y4roslav Avatar asked Nov 06 '12 11:11

y4roslav


People also ask

What is the difference between array and hash in Ruby?

A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. Hashes enumerate their values in the order that the corresponding keys were inserted.

What is an empty array Ruby?

You can create an empty array by creating a new Array object and storing it in a variable. This array will be empty; you must fill it with other variables to use it. This is a common way to create variables if you were to read a list of things from the keyboard or from a file.

Does Ruby have arrays?

An array is a data structure that represents a list of values, called elements. Arrays let you store multiple values in a single variable. In Ruby, arrays can contain any data type, including numbers, strings, and other Ruby objects.


1 Answers

The method returns true if the block never returns false or nil.

So since the block never gets called, of course it never returns false or nil, thus all returns true.

The same goes for any:

The method returns true if the block ever returns a value other than false or nil.

Since the block never gets called, it never returns a value other than false or nil, thus any returns false.

like image 134
Kim Stebel Avatar answered Oct 06 '22 00:10

Kim Stebel