92

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.

2

3 Answers 3

206

Have you tried this:

@emails.join(",")
Sign up to request clarification or add additional context in comments.

2 Comments

join is an alias for *, so this is just repeating the OP's question.
But join is certainly easier to understand.
17

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.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.