Ruby output contents of an array as a comma separated string Ruby

RubyArraysRuby on-Rails-3

Ruby Problem Overview


Is there a more correct way to output the contents of an array as a comma delimited string

@emails = ["[email protected]", "[email protected]", "[email protected]"]

@emails * ","

=> "[email protected]", "[email protected]", "[email protected]"

This works but I am sure there must be a more elegant solution.

Ruby Solutions


Solution 1 - Ruby

Have you tried this:

@emails.join(",")

Solution 2 - Ruby

Though the OP and many answers imply that the array always has content, sometimes I find myself needing to join a list that may contain "empty" elements (typically for concatenating data for a UI).

Here is little "progression" of how different approaches handle such an "imperfect" array of strings:

['a','b','',nil].join(',') # => "a,b,," 
['a','b','',nil].compact.join(',') # => "a,b,"
['a','b','',nil].compact.reject(&:empty?).join(',') # => "a,b"
['a','b','',nil].reject(&:blank?).join(',') # Rails only

The last one being my favorite (Rails) approach.

Solution 3 - Ruby

I just had to do something similar in an ERB template using AllowedUsers <%= _allowed_users.join(" ") %>. It might not be as elegant as you were looking for, but it's the same implementation I've seen in several languages, so that might be a win for readability.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchellView Question on Stackoverflow
Solution 1 - RubyHenrikView Answer on Stackoverflow
Solution 2 - RubyJon KernView Answer on Stackoverflow
Solution 3 - RubyFraqView Answer on Stackoverflow