简短高效的 Ruby 代码,用于将单词数组转换为混洗和逗号分隔的字符串,在最后一个单词之前有一个 "and"?

Short and efficient Ruby code for transforming array of words to shuffled and comma separated string, with an "and" before the last word?

我想转换这样的数组:

["apple","banana","pineapple","plum","pear"]

I like plum, pineapple, banana, pear *and* apple.

我现在的代码是这样的:

%Q{
   I like #{%w[apple banana pineapple plum pear].shuffle.yield_self{|q| [q[0..-2].join(", "),q[-1]].join(" and ") }}
  }

是否有更多的 %w[聪明、干净、简短、高效的 ruby​​esque].magic() 方法?

我不知道这是否更聪明或更清洁,但我们开始吧:

def to_sentence(ary)
  ary = ary.dup.shuffle
  [ary.pop, ary.join(', ')].reverse.join(' and ')
end

我想提供两个解决方案。两者都不改变作为参数传递给方法的数组。

arr = ["apple", "banana", "pineapple", "plum", "pear"]

#1

 def to_sentence(arr)
  *all_but_last, last = arr.shuffle
  all_but_last.join(', ') << ' and ' << last
end
to_sentence(arr)
  #=> "pear, plum, pineapple, apple and banana"
to_sentence(arr)
  #=> "banana, pear, pineapple, plum and apple"
to_sentence(arr)
  #=> "banana, plum, apple, pineapple and pear"
to_sentence(arr)
  #=> "banana, pineapple, pear, apple and plum"

#2

 def to_sentence(arr)
  arr.shuffle.join(', ').sub(/,(?!.*,)/, ' and')
 end
 to_sentence(arr)
   #=> "banana, plum, pear, apple and pineapple"
 to_sentence(arr)
   #=> "pear, plum, pineapple, banana and apple"
 to_sentence(arr)
   #=> "apple, pineapple, plum, pear and banana"
 to_sentence(arr)
   #=> "apple, plum, pear, pineapple and banana"

正则表达式匹配字符串中后面没有跟有另一个逗号的逗号(即匹配字符串中的最后一个逗号)。 (?!.*,) 是一个 负前瞻 .

正则表达式也可以这样写

/.*\K,/

.* 匹配行终止符以外的任何字符,尽可能多(包括逗号),因为 * 默认是 greedy\K 然后将匹配的开始重置为字符串中的当前位置(就在最后一个逗号之前),并从返回的匹配中丢弃任何先前使用的字符。然后匹配一个逗号,它必然是字符串中的最后一个逗号。