Skip to main content

Command Palette

Search for a command to run...

Ruby: Using .all? when the variable can be an empty array

Published
1 min read
Ruby: Using .all? when the variable can be an empty array

Context

You have an array of hashes and want to check if all elements are satisfying a condition.

TIL

You might want to do this in Ruby:

objects.all? { _1[:amount] > 10 }

In this case, you should remember according to with the documentation .all? might return true in this case:

[].all? 
# returns true

So this thing might happen

array = []

array.all? { _1[:amount] > 1}
# will return true

array.all? { _1[:this_key_does_not_exists] > 1}
# will return true

Quick fix

Use

array.present? && array.all? { _1[:key_does_not_exist] > 1}

Explanation:

First check if the array is not empty and then try to apply the condition to all elements.

More from this blog

All about code - Ruby and Rails technical content written by Lucian Ghinda

101 posts

I write here quick thoughts, ideas, tips, and learnings about programming, programmers, and building software. Most of my focus is on Ruby, Rails, Hotwire, and everything about web applications.