通过遍历获取客户的to_s方法
有没有一种Ruby习惯用法可以在1行(或少于3行代码)中编写代码?
def method
string = ""
@customers.each { |customer| string += customer.to_s + "\n" }
string
end发布于 2010-05-27 18:02:28
@customers.join("\n") + "\n"join通过对每个不是字符串的元素调用to_s并将其插入到由join (在本例中为\n)的参数分隔的新字符串中,从数组创建字符串。由于您的代码还在末尾添加了一个\n (而join没有),因此您需要在调用join之后添加+ "\n"以获得相同的行为。
发布于 2010-05-27 18:02:32
我想你想要像这样的
@customers.join("\n")发布于 2010-05-28 02:22:04
主要是为了好玩,并以@sepp2k的答案为基础:
"#{@customers.join "\n"}\n"我非常喜欢嵌入式字符串语法,因为如果您想要其他页眉/页脚文本,它很容易在以后扩展。
https://stackoverflow.com/questions/2920071
复制相似问题