"a, b, and c" 我记得 rub-6ren">
gpt4 book ai didi

ruby - 创建一个人类可读的列表,在 ruby​​ 列表的最后一个元素之前插入 "and"

转载 作者:数据小太阳 更新时间:2023-10-29 06:45:25 24 4
gpt4 key购买 nike

如何将列表变成逗号分隔的字符串,并在数组中的最后一个元素之前加上“and”?

像这样:

list1 = ['a','b','c']

然后把它变成这样:

=> "a, b, and c"

我记得 ruby​​ 有一个方法可以做到这一点。然而我已经搜索过了,并没有找到它。感谢您的帮助。

最佳答案

尝试:[list[0...-1].join(", "), list.last].join(", and ")

编辑:Rails 有您可能正在寻找的方法,称为 to_sentence .

如果您没有 Rails 或不想依赖 Rails,请打开 Array 类并包含上述方法,例如:

class Array
def join_all(join_with = ", ", connector = "and", last_comma = false)
return self.to_s if self.empty? || self.size==1
connector = join_with+connector if last_comma
[list[0...-1].join(join_with), list.last].join(connector)
end
end

关于ruby - 创建一个人类可读的列表,在 ruby​​ 列表的最后一个元素之前插入 "and",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6737299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com