以逗号分隔的字符串形式输出数组的内容

是否有更正确的方法将数组的内容输出为逗号分隔的字符串

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


@emails * ","


=> "joe@example.com", "Peter@example.com", "alice@example.com"

这是可行的,但我相信一定有更优雅的解决方案。

92703 次浏览

Have you tried this:

@emails.join(",")

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.

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.