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)