1
votes

I want to remove the last comma in the array. For example, self.committed.join(', ').titleize produces "Sun, Mon, Tue, Wed, Thu, Fri, Sat,".

I don't know if the answer is somehow removing the empty "" at the end of the array ["sun", "mon", "tue", "wed", "thu", "fri", "sat", ""] so that way I can use to_sentence and it won't come out looking like this "Sun, Mon, Tue, Wed, Thu, Fri, Sat, And"

Or if there is a way with join to prevent the additional comma?

model

serialize :committed, Array

db

t.text     "committed",       default: "---\n- sun\n- mon\n- tue\n- wed\n- thu\n- fri\n- sat\n"

I don't want to change serialize or the db, but I'm open to it as a last resort.

1
You seem to approach this from the wrong end. Your string contains a trailing comma just because the array contains an empty string. So the actual problem is not join, but your array content. You should figure out where this extra "" comes from and eliminate it. Maybe add a validation to your model to disallow empty array values (or restrict them to abbreviated weekdays). BTW, the YAML database default does not contain the empty string.Stefan

1 Answers

3
votes

It's not clear why the array has an empty string as the last element, but it's easy to skip it:

self.committed[0..-2].to_sentence.titleize

Or:

self.committed.reject(&:blank?).to_sentence.titleize

The latter will skip all blank elements, whereas the former will skip the last element regardless of its content.

If you want to individually capitalize the words before calling to_sentence (to avoid "and" being capitalized), just use map:

self.committed[0..-2].map(&:titleize).to_sentence