Jeremy Smith Jeremy Smith - 2 years ago 60
Ruby Question

Is there a way to conditionally add to an array in one line?

I have str1 and str2. str1 may or not be an empty string, and I want to construct an array like:

str1 = ""
str2 = "bar"


str1 = "foo"
str2 = "bar"
["foo", "bar"]

I can only figure out a way to do this on two lines right now but I know there must be a way to do it one.

Answer Source
[str1, str2].reject {|x| x==''}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download