Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate many boolean expressions like Array#join in Ruby

In Ruby, you can use Array#join to simple join together multiple strings with an optional delimiter.

[ "a", "b", "c" ].join        #=> "abc"
[ "a", "b", "c" ].join("-")   #=> "a-b-c"

I'm wondering if there is nice syntactic sugar to do something similar with a bunch of boolean expressions. For example, I need to && a bunch of expressions together. However, which expressions will be used is determined by user input. So instead of doing a bunch of

cumulative_value &&= expression[:a] if user[:input][:a]

I want to collect all the expressions first based on the input, then && them all together in one fell swoop. Something like:

be1 = x > y
be2 = Proc.new {|string, regex| string =~ regex}
be3 = z < 5 && my_object.is_valid?
[be1,be2.call("abc",/*bc/),be3].eval_join(&&)

Is there any such device in Ruby by default? I just want some syntatic sugar to make the code cleaner if possible.

like image 947
istrasci Avatar asked Jan 14 '13 22:01

istrasci


People also ask

How do you evaluate a Boolean expression?

A Boolean expression will be evaluated to either true or false if all of its variables have been substituted with their actual values. For example, a Boolean variable x is a Boolean expression, and it can be evaluated to true or false subject to its actual value.

Can you have an array of Boolean?

Boolean arrays are arrays that contain values that are one of True or False. This has a True value at the positions of elements > 3, and False otherwise.

What operators are used to evaluate Boolean expressions?

Comparison operators such as = , < , > , <> , <= , and >= produce Boolean expressions by comparing the expression on the left side of the operator to the expression on the right side of the operator and evaluating the result as True or False .


1 Answers

Try Array#all?. If arr is an Array of booleans, this works by itself:

arr.all?

will return true if every element in arr is true, or false otherwise.

You can use Array#any? in the same manner for joining the array on ||, that is, it returns true if any element in the array is true and false otherwise.

This will also work if arr is an array of Procs, as long as you make sure to pass the correct variables to Proc#call in the block (or use class, instance, or global variables).

like image 198
Reinstate Monica -- notmaynard Avatar answered Sep 21 '22 18:09

Reinstate Monica -- notmaynard