Ruby 将数组的内容输出为逗号分隔的字符串 Ruby
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7146353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby output contents of an array as a comma separated string Ruby
提问by chell
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.
这有效,但我确信必须有一个更优雅的解决方案。
回答by Henrik
Have you tried this:
你有没有试过这个:
@emails.join(",")
回答by Jon Kern
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).
尽管 OP 和许多答案暗示数组总是有内容,但有时我发现自己需要加入一个可能包含“空”元素的列表(通常用于连接 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.
最后一个是我最喜欢的(Rails)方法。
回答by Fraq
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.
我只需要在 ERB 模板中使用AllowedUsers <%= _allowed_users.join(" ") %>. 它可能不像您所寻找的那样优雅,但它与我在多种语言中看到的实现相同,因此这可能是可读性的胜利。

