DEV Community

n350071πŸ‡―πŸ‡΅
n350071πŸ‡―πŸ‡΅

Posted on

.all? method of Enumerable for Array, Hash in Ruby is awesome!

What is .all?

https://ruby-doc.org/core-2.7.0/Enumerable.html

πŸ€” Situations1: Stop the short circuit evaluation ( && )

Because .valid? has side effect and they want all of forms to evaluate validation, they can't use &&.

@form_a.valid? & @form_b.valid?  # πŸ€” evaluate both of valid? but using & is not natual
@form_a.valid? && @form_b.valid? # πŸ€” evaluate only forward if it is false

πŸ‘ Solve it

forms = [@form_a.valid?, @form_b.valid?]
(forms.map(&:valid?)).all?

πŸ€” Situation2: isn't there any errors?

valid = true
users.each do |user|
  valid = false unless user.valid?
end
valid

πŸ‘ Solve it

users.map{ |user| user.valid? }.all?

Top comments (0)