Im on rails 4. I have an each block like this
blends.addons.each do |a|
....
end
Lets say I have a blend called "test" with three add-ons
I want to create a sentence in my blends show.html.erb that reads like this
A test blend with vanilla, chocolate and cinnamon
My code to form this sentence would be something like
A <%= blend.name %> blend with <%= blend.addons.each do |a| %><%= a.name+", " %><% end %>
That code will just print out the names of all the addons attached to the blend separated by commas. How would I make my each block add commas up until the last element, then print "and #{the last element}"? Or is an each block not the best way to go about it? Thanks.
This is provided by an ActiveSupport method:
%w(Earth Wind Fire).to_sentence # => "Earth, Wind, and Fire"
You can configure it, see doc
In your case, I'd say:
%w(Earth Wind Fire).to_sentence(last_word_connector: ' and ')
# => "Earth, Wind and Fire"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With