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?
To convert an array to a comma-separated string, call the join() method on the array, passing it a string containing a comma as a parameter. The join method returns a string containing all array elements joined by the provided separator.
Ruby | Array class join() function join() is an Array class method which returns the string which is created by converting each element of the array to a string, separated by the given separator.
The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
When you want just the comma character ( , ) to appear as the separator between items in the list, use . join(",") to convert the array to a string. As you can see, there will never be an extra comma after the last item, meaning your entire array is now joined together as one string.
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"
I think you have nil elements in your array. You can do this:
arr.compact.join(", ")
It seems you need to compact
the array before join
. It returns a copy of array without nil
elements.
http://ruby-doc.org/core-2.2.0/Array.html#method-i-compact
[1,nil,2,3].compact.join(', ')
You can also use compact!
to remove the nil
elements from the source array itself (without making a copy).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With