Skip to content

Instantly share code, notes, and snippets.

@jguitar
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jguitar/8021670b65b231bb1694 to your computer and use it in GitHub Desktop.
Save jguitar/8021670b65b231bb1694 to your computer and use it in GitHub Desktop.
join words with commas and a final connector

all samples with I18n.locale = :es

before

brew code, a lot of possible errors

def join_items(collection)
  return collection.first if collection.size == 1
  
  all_but_last = collection.take(collection.size - 1)
  [all_but_last.join(', '), collection.last].join(' y ')
end

join_items(%w(foo bar baz))

$=> "foo, bar y baz"

after

using to_sentence from ActiveSupport

%w(foo bar baz).to_sentence

$=> "foo, bar, y baz"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment