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.
be1
does not make sense unlessx
andy
are already given, in which case it will be a constant of eithertrue
orfalse
, butbe2
is a proc, which always evaluates to a truethy value, which is also a constant, and would not make much sense unless you are going to apply that to some arguments. It seems you are mixing these.