[Ruby] to_sentence
常常看到收集 error 的 code 會這樣寫
errors.full_messages.to_sentence
to_sentence 是用來做什麼的呢?
來看一下官方飯粒
[].to_sentence # => ""
['one'].to_sentence # => "one"
['one', 'two'].to_sentence # => "one and two"
['one', 'two', 'three'].to_sentence # => "one, two, and three"
['one', 'two'].to_sentence(passing: 'invalid option')
# => ArgumentError: Unknown key :passing
['one', 'two'].to_sentence(two_words_connector: '-')
# => "one-two"
['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ')
# => "one or two or at least three"
可以看到,使用 to_sentence 會幫我們將 array 轉為 string 每個 string 中間加上逗號,最後一個 string 前會加上 and
不想要逗號當然也有參數可以進行調整