0

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"]
sawa
  • 165,429
  • 45
  • 277
  • 381
Costy
  • 165
  • 2
  • 14

3 Answers3

4

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]]
sawa
  • 165,429
  • 45
  • 277
  • 381
  • *("bbb" if false) what exactly mean *, Could you send link to description this notation? – Costy Oct 11 '18 at 10:21
  • 1
    That is called the splat. You can read [my answer to another question](https://stackoverflow.com/questions/5781639/passing-multiple-error-classes-to-rubys-rescue-clause-in-a-dry-fashion/5782805#5782805) for reference. – sawa Oct 11 '18 at 10:22
2

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]
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
1

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"]
Kimmo Lehto
  • 5,910
  • 1
  • 23
  • 32