How to avoid short-circuit evaluation on

2020-06-07 02:50发布

I'm working with Ruby on Rails and would like to validate two different models :

if (model1.valid? && model2.valid?)
...
end

However, "&&" operator uses short-circuit evaluation (i.e. it evaluates "model2.valid?" only if "model1.valid?" is true), which prevents model2.valids to be executed if model1 is not valid.

Is there an equivalent of "&&" which would not use short-circuit evaluation? I need the two expressions to be evaluated.

5条回答
冷血范
2楼-- · 2020-06-07 03:00

Instead of creating an extra array with map, you can pass a block to all?.

[model_instance_1, model_instance_2].all? {|i| i.valid? }
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-06-07 03:04

Try this:

([model1, model2].map(&:valid?)).all?

It'll return true if both are valid, and create the errors on both instances.

查看更多
手持菜刀,她持情操
4楼-- · 2020-06-07 03:04

How about:

if [model1.valid?,model2.valid?].all?
  ...
end

Works for me.

查看更多
Fickle 薄情
5楼-- · 2020-06-07 03:05

& works just fine.

irb(main):007:0> def a
irb(main):008:1> puts "a"
irb(main):009:1> false
irb(main):010:1> end
=> nil

irb(main):011:0> def b
irb(main):012:1> puts "b"
irb(main):013:1> true
irb(main):014:1> end
=> nil

irb(main):015:0> a && b
a
=> false

irb(main):016:0> a & b
a
b
=> false

irb(main):017:0> a and b
a
=> false
查看更多
Deceive 欺骗
6楼-- · 2020-06-07 03:06

Evaluate them separately and store the result in a variable. Then use a simple && between those booleans :)

查看更多
登录 后发表回答