GhostRider GhostRider - 6 days ago 7
Ruby Question

Array join with commas, only when element is not nil

Is there a starightforward way to achieve

array.join(", ")
where the comma is only included between elements that exist? I.e., if some elements don't exist in the array, I don't end up getting orphan commas?

Sid Sid
Answer

Example:

["", nil, "test word", 5, 7, nil, "", nil, "", 7, 6, ""] => "test word, 5, 7, 7, 6"

Edit: Please note that the first method here requires Ruby on Rails. Use the second method for a Ruby-only solution

You can try this to remove both nil and empty strings "" and then join with commas (It removes all nil values with compact, then it does split on "" to create a two-dimensional array where any "" elements in the first array are just empty arrays in the new 2D array, then it does flatten which turns the 2D array back into a normal array but with all the empty arrays removed, and finally it does the join(", ") on this array):

> array.compact.split("").flatten.join(", ")


array = ["", nil, "test word", 5, 7, nil, "", nil, "", 7, 6, ""]

array.compact => ["", "test word", 5, 7, "", "", 7, 6, ""].split("") => [[], ["test word", 5, 7], [], [7, 6], []].flatten => ["test word", 5, 7, 7, 6].join(", ") => "test word, 5, 7, 7, 6"

Edit: Another way would be:

> array.reject(&:blank?).join(", ")


array = ["", nil, "test word", 5, 7, nil, "", nil, "", 7, 6, ""]

array.reject(&:blank?) => ["test word", 5, 7, 7, 6].join(", ") => "test word, 5, 7, 7, 6"
Comments