Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/powerpack/string/blank.rb,
lib/powerpack/string/format.rb,
lib/powerpack/string/squish.rb,
lib/powerpack/string/strip_indent.rb,
lib/powerpack/string/strip_margin.rb

Instance Method Summary collapse

Instance Method Details

#blank?Boolean

Checks whether a string is blank. A string is considered blank if it is either empty or contains only whitespace characters.

Examples:

''.blank? #=> true
'    '.blank? #=> true
'  test'.blank? #=> false

Returns:

  • (Boolean)

    true is the string is blank, false otherwise



16
17
18
# File 'lib/powerpack/string/blank.rb', line 16

def blank?
  empty? || strip.empty?
end

#format(*args) ⇒ String

A nicer alternative to Kernel#sprintf and String#%.

Examples:

'This is %s!'.format('Sparta') #=> 'This is Sparta!'
'My name is %{fname} %{lname}.'.format(fname: 'Bruce', lname: 'Wayne')
#=> 'My name is Bruce Wayne.'
'%d + %d'.format([1, 2]) #=> '1 + 2'

Returns:

  • (String)

    the formatted string



16
17
18
# File 'lib/powerpack/string/format.rb', line 16

def format(*args)
  super(self, *(args.flatten(1)))
end

#squishString

Strips leading and trailing whitespace and squashes internal whitespace.

Examples:

' Peter   Parker'.squish #=> 'Peter Parker'

Returns:

  • (String)

    a new string with no leading and trailing whitespace and no consecutive whitespace characters inside it



10
11
12
# File 'lib/powerpack/string/squish.rb', line 10

def squish
  dup.squish!
end

#squish!String

Strips leading and trailing whitespace and squashes internal whitespace.

Examples:

' Peter   Parker'.squish #=> 'Peter Parker'

Returns:

  • (String)

    the string with no leading and trailing whitespace and no consecutive whitespace characters inside it



21
22
23
24
25
# File 'lib/powerpack/string/squish.rb', line 21

def squish!
  strip!
  gsub!(/\s+/, ' ')
  self
end

#strip_indentObject

The method strips the whitespace preceding the base indentation. Useful for HEREDOCs and other multi-line strings.

Examples:


code = "  def test\n    some_method\n    other_method\n  end\n".strip_indent

#=> "def\n  some_method\n  \nother_method\nend"


16
17
18
19
20
# File 'lib/powerpack/string/strip_indent.rb', line 16

def strip_indent
  leading_space = scan(/^[ \t]*(?=\S)/).min
  indent = leading_space ? leading_space.size : 0
  gsub(/^[ \t]{#{indent}}/, '')
end

#strip_margin(margin_characters) ⇒ Object

The method strips the characters preceding a special margin character. Useful for HEREDOCs and other multi-line strings.

Examples:


code = "  |def test\n  |  some_method\n  |  other_method\n  |end\n".strip_margin('|')

#=> "def\n  some_method\n  \nother_method\nend"


16
17
18
19
# File 'lib/powerpack/string/strip_margin.rb', line 16

def strip_margin(margin_characters)
  margin = Regexp.quote(margin_characters)
  gsub(/^\s+#{margin}/, '')
end