Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add String#squish

  • Loading branch information...
commit 38791c478ae483b386539acc4dd5904cece25c1c 1 parent 581df69
@bbatsov authored
View
1  README.md
@@ -28,6 +28,7 @@ Or install it yourself as:
* [#format](http://rdoc.info/github/bbatsov/powerpack/String#format-instance_method)
* [#strip_indent](http://rdoc.info/github/bbatsov/powerpack/String#strip_indent-instance_method)
* [#strip_margin](http://rdoc.info/github/bbatsov/powerpack/String#strip_margin-instance_method)
+ * [#squish](http://rdoc.info/github/bbatsov/powerpack/String#squish-instance_method)
## Documentation
View
1  lib/powerpack/string.rb
@@ -2,3 +2,4 @@
require_relative 'string/format'
require_relative 'string/strip_indent'
require_relative 'string/strip_margin'
+require_relative 'string/squish'
View
14 lib/powerpack/string/squish.rb
@@ -0,0 +1,14 @@
+unless String.method_defined? :squish
+ class String
+ # Strips leading and trailing whitespace and squashes internal whitespace.
+ #
+ # @return [String] a string with not leading and traling whitespace and no
+ # consecutive whitespace characters inside it
+ #
+ # @example
+ # ' Peter Parker'.squish #=> 'Peter Parker'
+ def squish
+ strip.gsub(/\s+/, ' ')
+ end
+ end
+end
View
11 spec/powerpack/string/squish_spec.rb
@@ -0,0 +1,11 @@
+require 'spec_helper'
+
+describe 'String#squish' do
+ it 'strips leading and trailing whitespace' do
+ expect(' Peter '.squish).to eq('Peter')
+ end
+
+ it 'compacts internal whitespace' do
+ expect("Peter\r\n \t Parker".squish).to eq('Peter Parker')
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.