Skip to content

Instantly share code, notes, and snippets.

@lukeledet
Created July 13, 2011 20:44
Show Gist options
  • Save lukeledet/1081280 to your computer and use it in GitHub Desktop.
Save lukeledet/1081280 to your computer and use it in GitHub Desktop.
String#rejoin
# Split a string by regular expression, run the block on each element, then
# join the pieces back together with the right separators.
#
# Example:
# >> "Internationalization's awesome.".rejoin(/\W/) {|x| x.length > 2 ? "#{x[0]}#{x.length - 2}#{x[-1]}" : x }
# => "I18n's a5e."
class String
def rejoin(sep, &block)
separators = self.scan sep
self.split(sep).map(&block).zip(separators).flatten.compact.join
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment