Railsで配列の要素から"A, B, and C"形式の文字列を作る時はArray#to_sentenceが便利

はじめに

タイトル通りです。
最初は自分で実装しようと思ったんですが意外とめんどいことに気付き、色々探していたら該当の処理をよしなにやってくれるメソッドを見つけたのでまとめました。

Array#to_sentence

Array#to_sentenceは、ActiveSupportArray拡張で、配列の要素から"A, B, and C"形式の文字列を組み立ててくれるメソッドです。
引数に何も渡さずに実行すると、配列の要素から"A, B, and C"形式の文字列を返します。

%w(one).to_sentence
# => "one"
%w(one two).to_sentence
# => "one and two"
%w(one two three).to_sentence
# => "one, two, and three"

また、オプションを使うことで"and"以外の接続詞を使ったり、最後の要素の接続詞の前のカンマを取ることもできます。

%w(one two).to_sentence(two_words_connector: ' or ')
# => "one or two"
%w(one two three).to_sentence(last_word_connector: ' and ')
# => "one, two and three"

べんりだ!

おわりに

いつも思うんですけど、ActiveSupportのかゆいところに手が届く感はんぱないですよね、、

参考