How can I add value to an array inline under some condition?
This example:
["aaa", ("bbb" if false)]
# => ["aaa", nil]
adds nil
, but, I do not want to add anything:
["aaa"]
How can I add value to an array inline under some condition?
This example:
["aaa", ("bbb" if false)]
# => ["aaa", nil]
adds nil
, but, I do not want to add anything:
["aaa"]
You either do:
["aaa", ("bbb" if false)].compact
or:
["aaa", *("bbb" if false)]
But be careful with certain classes when you use the second option, as it may mess up objects of certain classes. For example, a hash would be converted into an array:
["aaa", *({b: :b} if true)]
# => ["aaa", [:b, :b]]
I would even post this as an answer since that’s a most succinct and clean way to accomplish this task.
["aaa"].tap { |arr| arr << "bbb" if false }
In more generic and easy to follow way:
input = [42]
to_add = {true: :true, false: :false}
to_add.each do |needed, value|
input.tap { |arr| arr << value if needed }
end
#⇒ [42, :true]
You could concat an empty array when the condition is false, which essentially does nothing:
["aaa"] + (1==1 ? ["foo"] : [])
=> ["aaa", "foo"]
["aaa"] + (1==2 ? ["foo"] : [])
=> ["aaa"]