All about coding

Ruby and Rails technical content written by Lucian Ghinda

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

#ruby #ruby-on-rails #programming-tips #til #coding

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.

View posts by tag

#ruby #concurrency #general-advice #life-hack #ruby-on-rails #google-cloud #kubernetes #bash #apis #rest-api #guide #docker #bugs-and-errors #howtos #newbie #programming-languages #programming-tips #til #coding #learning #postgresql #sql #design-patterns #web-api #programming-blogs #programmer #databases #programming #learn-coding #learning-journey #side-project #coding-challenge #design-principles #solid-principles #git #tips #testing #test-driven-development #test-automation #code #shortpost #refactoring #code-review #rails #developer #documentation #focus #blogging #content-creation #share #advice #newsletter #active-record #ai #ai-tools #generative-ai #web-development #errors #cursor-ide #ides #gpt-4 #news #scalability #tailwind-css #chatgpt #opensource #reviews #startups #github #technology #types #sorbet #performance #rubymine #vscode #codesnippet #features #syntax #friendlyrb #conference #directories #writing #summary #animation #articles #podcasts #publishing #patterns #pattern-matching #content #updates #seo-for-developers #marketing #properties #gems #matching #rspec #llm #tools #lsp #claudeai #opencode #mcp #rubocop #quality #planning #products #mvp #upgrade #agentic-ai #skills #superpowers