Class: String

Inherits:
Object show all
Defined in:
lib/r2-oas/lib/core_ext/string/filters.rb,
lib/r2-oas/lib/core_ext/object/blank.rb

Overview

Constant Summary collapse

BLANK_REGEXP =
/\A[[:space:]]*\z/

Instance Method Summary collapse

Instance Method Details

#blank?true, false

A string is blank if it’s empty or contains whitespaces only:

''.blank?       # => true
'   '.blank?    # => true
"\t\n\r".blank? # => true
' blah '.blank? # => false

Unicode whitespace is supported:

"\u00a0".blank? # => true

Returns:

  • (true, false)


119
120
121
# File 'lib/r2-oas/lib/core_ext/object/blank.rb', line 119

def blank?
  BLANK_REGEXP === self
end

#squishObject

Returns the string, first removing all whitespace on both ends of the string, and then changing remaining consecutive whitespace groups into one space each.

Note that it handles both ASCII and Unicode whitespace.

%{ Multi-line
   string }.squish                   # => "Multi-line string"
" foo   bar    \n   \t   boo".squish # => "foo bar boo"


15
16
17
# File 'lib/r2-oas/lib/core_ext/string/filters.rb', line 15

def squish
  dup.squish!
end

#squish!Object

Performs a destructive squish. See String#squish.

str = " foo   bar    \n   \t   boo"
str.squish!                         # => "foo bar boo"
str                                 # => "foo bar boo"


23
24
25
26
27
28
# File 'lib/r2-oas/lib/core_ext/string/filters.rb', line 23

def squish!
  gsub!(/\A[[:space:]]+/, '')
  gsub!(/[[:space:]]+\z/, '')
  gsub!(/[[:space:]]+/, ' ')
  self
end