TODAY I LEARNED

Enumerable#any? and Enumerable#detect

Someone told me #any? didn't stop iterating after finding the first truthy value, that I should use #detect instead, but turns out both methods behave the same, at least in Ruby 3.0.1.

Try running this for example:

(1..5).to_a.any? do |n|
  puts n
  true
end

(1..5).to_a.detect do |n|
  puts n
  true
end

You'll see this:

1
1

Tweet

Learned by kevin-perez on Oct 20, 2022

Discover our latest blog posts
  • #ruby
  • view raw
  • permalink
  • 2 likes
previous TIL next TIL
  • Log in
  • ?

    TIL is an open-source project by MagmaLabs that exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any MagmaLaber as well as selected friends of MagmaLabs. We hope you enjoy learning along with us.

    • /wearemagmalabs
  • statistics
  • search
  • Twitter