Created
July 13, 2011 20:44
-
-
Save lukeledet/1081280 to your computer and use it in GitHub Desktop.
String#rejoin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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