First of all I found two useful articles in documentations about these methods:
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?
?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With