Ruby Comma Separated Array Ruby Output Contents

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

@emails = ["joe@example.com", "Peter@example.com", "alice@example.com"] @emails * "," => "joe@example.com", "Peter@example.com", "alice@example.com" 

This works, but I'm sure there should be a more elegant solution.

+58
arrays ruby ruby-on-rails-3
Aug 22 '11 at 10:50
source share
3 answers

Have you tried this:

 @emails.join(",") 
+140
Aug 22 '11 at 10:52
source share

Although the OP and many answers imply that the array always has content, sometimes I need to join a list that may contain "empty" elements (usually to concatenate data for the user interface).

There is little "progression" of how different approaches process 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 is my favorite (Rails).

+3
Dec 11 '16 at 23:02
source share

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

+1
Apr 14 '15 at 17:09
source share



All Articles