Module: Regex::String

Included in:
String
Defined in:
lib/regex/string.rb

Overview

Extensions for String class. These methods are taken directly from Ruby Facets.

Instance Method Summary collapse

Instance Method Details

#indent(n) ⇒ Object

Indent left or right by n spaces. (This used to be called #tab and aliased as #indent.)

CREDIT: Gavin Sinclair
CREDIT: Trans


53
54
55
56
57
58
59
# File 'lib/regex/string.rb', line 53

def indent(n)
  if n >= 0
    gsub(/^/, ' ' * n)
  else
    gsub(/^ {0,#{-n}}/, "")
  end
end

#margin(n = 0) ⇒ Object

Provides a margin controlled string.

 x = %Q{
       | This
       |   is
       |     margin controlled!
       }.margin

 NOTE: This may still need a bit of tweaking.

CREDIT: Trans


21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/regex/string.rb', line 21

def margin(n=0)
  #d = /\A.*\n\s*(.)/.match( self )[1]
  #d = /\A\s*(.)/.match( self)[1] unless d
  d = ((/\A.*\n\s*(.)/.match(self)) ||
      (/\A\s*(.)/.match(self)))[1]
  return '' unless d
  if n == 0
    gsub(/\n\s*\Z/,'').gsub(/^\s*[#{d}]/, '')
  else
    gsub(/\n\s*\Z/,'').gsub(/^\s*[#{d}]/, ' ' * n)
  end
end

#tabto(n) ⇒ Object

Preserves relative tabbing. The first non-empty line ends up with n spaces before nonspace.

CREDIT: Gavin Sinclair


39
40
41
42
43
44
45
# File 'lib/regex/string.rb', line 39

def tabto(n)
  if self =~ /^( *)\S/
    indent(n - $1.length)
  else
    self
  end
end