Reputation: 1188
I have several records for an object (not all of them) that I have to check whether they're true or false, to mark another record true or false. This is what I'm doing right now:
step_finished = object.one == true && object.two == true && object.three == true && object.four == true
I'm sure there must be a better way but I haven't been able to find it. I have another step with 20 values to check, so if you know a more efficient way check this, please help!
Thanks!
Upvotes: 0
Views: 679
Reputation: 74595
You don't need to test for == true
; it is enough to simply test the "truthiness" of something. Anything that is not nil
or false
will evaluate to true
in a boolean context. So it is sufficient to do:
step_finished = object.one && object.two && object.three && object.four
You can also use all?
:
step_finished = [object.one, object.two, object.three, object.four].all?
Upvotes: 5
Reputation: 4847
As a variant you could use reduce
like this:
[object.one, object.two, object.three, object.four].reduce(:&)
to check if all elements in array are true
.
And you could use this:
[object.one, object.two, object.three, object.four].reduce(:|)
to check if at least one from them is true
.
Upvotes: 1
Reputation: 106802
step_finished = [:one, :two, :three, :four].all? { |attr| object.send(attr) }
Upvotes: 1
Reputation: 44360
any object in ruby return value like true, false, nil
-> == true
therefore unnecessary
put you record to array and check
[object.one, object.two, object.three, object.four].all?
all? method
Upvotes: 4