ruby - Why does .all? return true on an empty array? -


using ruby want evaluate items in array, , return true if pass conditional test.

i can using e.g. array.all? { |value| value == 2 }

so:

> array=[2,2] > array.all? { |value| value == 2 } => true > array=[2,3] > array.all? { |value| value == 2 } => false 

great!

but, why empty array pass test?

> array=[] > array.all? { |value| value == 2 } => true 

shouldn't return false?

and if need return false, how should modify method?

in ruby can never loop on empty collection (array, hashes, etc.), in case block never gets executed. , if block never gets executed, all? returns true (there no condition make result false).

read all? in the ruby documentation.

you can achieve goal by

  !array.empty? && array.all? { |value| value == 2 } 

Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -