使用“and"创建一个人类可读的列表插入到 ruby​​ 列表的最后一个元素之前 [英] Create a human-readable list with "and" inserted before the last element from a ruby list

查看:39
本文介绍了使用“and"创建一个人类可读的列表插入到 ruby​​ 列表的最后一个元素之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How would you take a list and make it into a comma-separated string, with "and" before the last element in the array?

采取类似的做法:

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

把它变成这样:

=> "a, b, and c"

我记得 ruby​​ 有一个方法.然而我已经搜索过了,没有找到.感谢您的帮助.

I remember ruby had a method for this. I've searched however, and couldn't find it. Thanks for the help.

推荐答案

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

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

Rails has the method you were probably looking for, called to_sentence.

如果你没有 Rails 或者不想依赖 Rails,打开 Array 类并包含上面的方法,比如:

In case you do not have Rails or do not wish to depend on Rails, open Array class and include the above method, like:

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

这篇关于使用“and"创建一个人类可读的列表插入到 ruby​​ 列表的最后一个元素之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆