Class: String

Inherits:
Object show all
Includes:
English::String, English::Style, English::Style::Replace, English::StyleORM, English::StyleORM::Replace, Random, Words
Defined in:
lib/gems/extlib-0.9.8/lib/extlib/blank.rb,
lib/mack-facets/extensions/string.rb,
lib/gems/extlib-0.9.8/lib/extlib/string.rb,
lib/gems/english-0.3.1/lib/english/roman.rb,
lib/gems/english-0.3.1/lib/english/style.rb,
lib/gems/english-0.3.1/lib/english/censor.rb,
lib/gems/english-0.3.1/lib/english/jumble.rb,
lib/gems/english-0.3.1/lib/english/string.rb,
lib/gems/english-0.3.1/lib/english/dresner.rb,
lib/gems/english-0.3.1/lib/english/inflect.rb,
lib/gems/english-0.3.1/lib/english/soundex.rb,
lib/gems/facets-2.4.5/lib/lore/facets/date.rb,
lib/gems/facets-2.4.5/lib/more/facets/succ.rb,
lib/gems/extlib-0.9.8/lib/extlib/inflection.rb,
lib/gems/facets-2.4.5/lib/core/facets/blank.rb,
lib/gems/facets-2.4.5/lib/more/facets/tuple.rb,
lib/gems/english-0.3.1/lib/english/metaphone.rb,
lib/gems/english-0.3.1/lib/english/style_orm.rb,
lib/gems/facets-2.4.5/lib/more/facets/random.rb,
lib/gems/english-0.3.1/lib/english/similarity.rb,
lib/gems/facets-2.4.5/lib/core/facets/boolean.rb,
lib/gems/facets-2.4.5/lib/more/facets/snapshot.rb,
lib/gems/facets-2.4.5/lib/more/facets/typecast.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/tab.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/xor.rb,
lib/gems/facets-2.4.5/lib/more/facets/htmlfilter.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/fold.rb,
lib/gems/facets-2.4.5/lib/more/facets/string/mask.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/align.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/bytes.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/chars.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/chomp.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/lines.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/mscan.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/nchar.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/range.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/to_re.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/words.rb,
lib/gems/facets-2.4.5/lib/more/facets/string/words.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/cleave.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/divide.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/natcmp.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/op_sub.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/splice.rb,
lib/gems/facets-2.4.5/lib/core/facets/comparable/cmp.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/bracket.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/pathize.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/rewrite.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/shatter.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/modulize.rb,
lib/gems/facets-2.4.5/lib/core/facets/comparable/bound.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/camelcase.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/each_char.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/each_word.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/line_wrap.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/methodize.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/snakecase.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/titlecase.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/word_wrap.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/start_with.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/variablize.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/capitalized.rb,
lib/gems/facets-2.4.5/lib/core/facets/string/interpolate.rb

Overview

Overload the standard String class for extra convienience.

Defined Under Namespace

Modules: Words Classes: Mask

Constant Summary collapse

BRA2KET =
{ '['=>']', '('=>')', '{'=>'}', '<'=>'>' }

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Words

#brief

Methods included from Random

append_features

Methods included from English::StyleORM::Replace

#camelize!, #classify!, #dasherize!, #foreign_key!, #humanize!, #tableize!, #titleize!, #underscore!

Methods included from English::StyleORM

#camelize, #classify, #dasherize, #foreign_key, #tableize, #titleize, #underscore

Methods included from English::String

#brief, #each_word_with_range

Methods included from English::Style::Replace

#camelcase!, #capitalcase!, #capitalize!, #demodulize!, #downcase!, #lowercase!, #methodize!, #modulize!, #ordinalize!, #pathize!, #snakecase!, #subcamelcase!, #titlecase!, #uncapitalcase!, #upcase!, #uppercase!

Methods included from English::Style

#capitalcase, #capitalize, #demodulize, #downcase, #lowercase, #ordinalize, #subcamelcase, #uncapitalize, #upcase, #uppercase

Class Method Details

.cast_from(object) ⇒ Object



218
219
220
221
222
223
# File 'lib/gems/facets-2.4.5/lib/more/facets/typecast.rb', line 218

def self.cast_from(object)
  return super
rescue TypeCastException
  return object.to_s if object.respond_to? :to_s
  raise
end

.interpolate(&str) ⇒ Object

Interpolate. Provides a means of extenally using Ruby string interpolation mechinism.

try = "hello"
str = "\#{try}!!!"
String.interpolate{ str }    #=> "hello!!!"

NOTE: The block neccessary in order to get
    then binding of the caller.

CREDIT: Trans


15
16
17
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/interpolate.rb', line 15

def self.interpolate(&str)
  eval "%{#{str.call}}", str.binding
end

.randomize(length = 10) ⇒ Object



110
111
112
113
114
115
# File 'lib/mack-facets/extensions/string.rb', line 110

def self.randomize(length = 10)
  chars = ("A".."H").to_a + ("J".."N").to_a + ("P".."T").to_a + ("W".."Z").to_a + ("3".."9").to_a
  newpass = ""
  1.upto(length) { |i| newpass << chars[rand(chars.size-1)] }
  return newpass.upcase
end

.translate(value) ⇒ Object

Overwrite this method to provide your own translations.



90
91
92
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 90

def self.translate(value)
  translations[value] || value
end

.translationsObject



94
95
96
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 94

def self.translations
  @translations ||= {}
end

Instance Method Details

#-(pattern) ⇒ Object

Removes occurances of a string or regexp.

"HELLO HELLO" - "LL"    #=> "HEO HEO"

CREDIT: Benjamin David Oakes


9
10
11
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/op_sub.rb', line 9

def -(pattern)
  self.gsub(pattern, '')
end

#/(o) ⇒ String

Returns The original path concatenated with o.

Examples:

"merb"/"core_ext" #=> "merb/core_ext"

Parameters:

  • o (String)

    The path component to join with the string.

Returns:

  • (String)

    The original path concatenated with o.



74
75
76
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 74

def /(other)
  File.join(self, other.to_s)
end

#^(aString) ⇒ Object

XOR two string.

TODO: This is used by crypt.rb, it needs to be documented.



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/xor.rb', line 7

def ^(aString)
  a = self.unpack('C'*(self.length))
  b = aString.unpack('C'*(aString.length))
  if (b.length < a.length)
    (a.length - b.length).times { b << 0 }
  end
  xor = ""
  0.upto(a.length-1) { |pos|
    x = a[pos] ^ b[pos]
    xor << x.chr()
  }
  return(xor)
end

#align(direction, n, sep = "\n", c = ' ') ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/align.rb', line 3

def align(direction, n, sep="\n", c=' ')
  case direction
  when :right
    align_right(n, sep="\n", c=' ')
  when :left
    align_left(n, sep="\n", c=' ')
  when :center
    align_center(n, sep="\n", c=' ')
  else
    raise ArgumentError
  end
end

#align_center(n, sep = "\n", c = ' ') ⇒ Object

Centers each line of a string.

The defualt alignment seperation is a new line ("/n") This can be changed as can be the padding string which defaults to a single space (' ').

s = "This is a test\nand\nso on\n"

puts s.align_center(14)

produces

This is a test
   and
  so on

CREDIT: Trans


97
98
99
100
101
102
103
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/align.rb', line 97

def align_center(n, sep="\n", c=' ')
  return center(n.to_i,c.to_s) if sep==nil
  q = split(sep.to_s).collect { |line|
    line.center(n.to_i,c.to_s)
  }
  q.join(sep.to_s)
end

#align_left(n, sep = "\n", c = ' ') ⇒ Object

Align a string to the left.

The defualt alignment seperation is a new line ("/n") This can be changes as can be the padding string which defaults to a single space (' ').

s = "This is a test\nand\nso on\n"

puts s.align_left(2)

produces

This is a test
and
so on

CREDIT: Trans


67
68
69
70
71
72
73
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/align.rb', line 67

def align_left(n, sep="\n", c=' ')
  return ljust(n.to_i,c.to_s) if sep==nil
  q = split(sep.to_s).collect { |line|
    line.ljust(n.to_i,c.to_s)
  }
  q.join(sep.to_s)
end

#align_right(n, sep = "\n", c = ' ') ⇒ Object

Align a string to the right. The defualt alignment seperation is a new line ("/n") This can be changes as can be the padding string which defaults to a single space (' ').

s = "This is a test\nand\nso on\n"

puts s.align_right(2)

produces

This is a test
           and
         so on

CREDIT: Trans


37
38
39
40
41
42
43
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/align.rb', line 37

def align_right(n, sep="\n", c=' ')
  return rjust(n.to_i,c.to_s) if sep==nil
  q = split(sep.to_s).collect { |line|
    line.rjust(n.to_i,c.to_s)
  }
  q.join(sep.to_s)
end

#blank?Boolean

Is this string just whitespace?

"abc".blank?  #=> false
"   ".blank?  #=> true

Returns:

  • (Boolean)


56
57
58
# File 'lib/gems/extlib-0.9.8/lib/extlib/blank.rb', line 56

def blank?
  strip.empty?
end

#bracket(bra, ket = nil) ⇒ Object

Return a new string embraced by given brakets. If only one bracket char is given it will be placed on either side.

"wrap me".bracket('{')        #=> "{wrap me}"
"wrap me".bracket('--','!')   #=> "--wrap me!"

CREDIT: Trans


14
15
16
17
18
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/bracket.rb', line 14

def bracket(bra, ket=nil)
  #ket = String.bra2ket[$&] if ! ket && /^[\[({<]$/ =~ bra
  ket = BRA2KET[bra] unless ket
  "#{bra}#{self}#{ket ? ket : bra}"
end

#bracket!(bra, ket = nil) ⇒ Object

Inplace version of #braket.

CREDIT: Trans


24
25
26
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/bracket.rb', line 24

def bracket!(bra, ket=nil)
  self.replace(bracket(bra, ket))
end

#bytesObject

Upacks string into bytes.



8
9
10
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/bytes.rb', line 8

def bytes
  self.unpack('C*')
end

#camel_caseString

Returns The string converted to camel case.

Examples:

"foo_bar".camel_case #=> "FooBar"

Returns:

  • (String)

    The string converted to camel case.



42
43
44
45
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 42

def camel_case
  return self if self !~ /_/ && self =~ /[A-Z]+.*/
  split('_').map{|e| e.capitalize}.join
end

#camelcase(upcase_first_letter = true) ⇒ Object

Converts a string to camelcase.

By default camelcase convert to UpperCamelCase, If an argument is set to false, then camelcase will produce lowerCamelCase.

camelcase also converts '/' to '::' which is useful for converting paths to namespaces.

Examples "camel_case".camelcase #=> "CamelCase" "camel/case".camelcase #=> "Camel::Case" "camel_case".camelcase(false) #=> "camelCase"



16
17
18
19
20
21
22
23
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/camelcase.rb', line 16

def camelcase(upcase_first_letter=true)
  up = upcase_first_letter
  str = dup
  str.gsub!(/\/(.?)/){ "::#{$1.upcase}" }  # NOT SO SURE ABOUT THIS -T
  str.gsub!(/(?:_+|-+)([a-z])/){ $1.upcase }
  str.gsub!(/(\A|\s)([a-z])/){ $1 + $2.upcase } if up
  str
end

#capitalized?Boolean

Return true if the string is capitalized, otherwise false.

"THIS".capitalized?  #=> true
"This".capitalized?  #=> true
"this".capitalized?  #=> false

CREDIT: Phil Tomson

Returns:

  • (Boolean)


11
12
13
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/capitalized.rb', line 11

def capitalized?
  self =~ /^[A-Z]/
end

#censor(rules) ⇒ Object Also known as: rewrite

Apply a set of rules (regular expression matches) to the string.

The rules must be applied in order! So we cannot use a hash because the ordering is not guaranteed! we use an array instead.

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
29
# File 'lib/gems/english-0.3.1/lib/english/censor.rb', line 22

def censor(rules)
  raise ArgumentError.new('rules parameter is nil') unless rules  # gmosx: helps to find bugs
  s = dup
  rules.each do |match,edit|
    s.gsub!(match,edit)
  end
  return s
end

#censor_words(&blk) ⇒ Object Also known as: word_filter

Filters out words from a string based on block test.

"a string".word_filter { |word| word =~ /^a/ }  #=> "string"


47
48
49
50
# File 'lib/gems/english-0.3.1/lib/english/censor.rb', line 47

def censor_words( &blk )
  s = self.dup
  s.censor_words!( &blk )
end

#censor_words!Object Also known as: word_filter!

In place version of #word_filter.

"a string".word_filter { |word| ... }

TODO: Surely this can be written better.



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/gems/english-0.3.1/lib/english/censor.rb', line 60

def censor_words! #:yield:
  rest_of_string = self
  wordfind = /(\w+)/
  offset = 0
  while wmatch = wordfind.match(rest_of_string)
    word = wmatch[0]
    range = offset+wmatch.begin(0) ... offset+wmatch.end(0)
    rest_of_string = wmatch.post_match
    self[range] = yield( word ).to_s
    offset = self.length - rest_of_string.length
  end
  self
end

#censored?(rules) ⇒ Boolean

Make sure the string passes a collection of censorship rules defined with reqular expressions.

Returns:

  • (Boolean)


36
37
38
39
40
41
# File 'lib/gems/english-0.3.1/lib/english/censor.rb', line 36

def censored?(rules)
  for r in rules
    return true if self =~ r
  end
  return false
end

#charsObject

Returns an array of characters.

"abc".chars  #=> ["a","b","c"]


9
10
11
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/chars.rb', line 9

def chars
  split(//)
end

#cleave(threshold = nil, len = nil) ⇒ Object

Cleave a string. Break a string in two parts at the nearest whitespace.

CREDIT: Trans



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/cleave.rb', line 8

def cleave(threshold=nil, len=nil)
  l = (len || size / 2)
  t = threshold || size

  h1 = self[0...l]
  h2 = self[l..-1]

  i1 = h1.rindex(/\s/) || 0
  d1 = (i1 - l).abs

  d2 = h2.index(/\s/) || l
  i2 = d2 + l

  d1 = (i1-l).abs
  d2 = (i2-l).abs

  if [d1, d2].min > t
    i = t
  elsif d1 < d2
    i = i1
  else
    i = i2
  end

  #dup.insert(l, "\n").gsub(/^\s+|\s+$/, '')
  return self[0..i].to_s.strip, self[i+1..-1].to_s.strip
end

#cmp(other) ⇒ Object

Compare method that takes length into account. Unlike #<=>, this is compatible with #succ.

"abc".cmp("abc")   #=>  0
"abcd".cmp("abc")  #=>  1
"abc".cmp("abcd")  #=> -1
"xyz".cmp("abc")   #=>  1

CREDIT Peter Vanbroekhoven


31
32
33
34
35
# File 'lib/gems/facets-2.4.5/lib/core/facets/comparable/cmp.rb', line 31

def cmp(other)
  return -1 if length < other.length
  return 1 if length > other.length
  self <=> other  # alphabetic compare
end

#compress_lines(spaced = true) ⇒ Object

Matches any whitespace (including newline) and replaces with a single space

Examples:

"  SELECT name\n  FROM users\n".compress_lines
=> "SELECT name FROM users"


106
107
108
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 106

def compress_lines(spaced = true)
  split($/).map { |line| line.strip }.join(spaced ? ' ' : '')
end

#constantizeObject

Returns a constant of the string.

Examples:

"User".constantize # => User
"HomeController".constantize # => HomeController
"Mack::Configuration" # => Mack::Configuration


98
99
100
# File 'lib/mack-facets/extensions/string.rb', line 98

def constantize
  Module.instance_eval("::#{self}")
end

#dequoteObject

Remove quotes from string.

"'hi'".dequite    #=> "hi"

CREDIT: Trans


88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/bracket.rb', line 88

def dequote
  s = self.dup

  case self[0,1]
  when "'", '"', '`'
    s[0] = ''
  end

  case self[-1,1]
  when "'", '"', '`'
    s[-1] = ''
  end

  return s
end

#divide(re) ⇒ Object

Breaks a string up into an array based on a regular expression. Similar to scan, but includes the matches.

s = "<p>This<b>is</b>a test.</p>"
s.divide( /\<.*?\>/ )

produces

["<p>This", "<b>is", "</b>a test.", "</p>"]

CREDIT: Trans


15
16
17
18
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/divide.rb', line 15

def divide( re )
  re2 = /#{re}.*?(?=#{re}|\Z)/
  scan(re2) #{re}(?=#{re})/)
end

#downcase?Boolean

Return true if the string is lowercase (downcase), otherwise false.

"THIS".downcase?  #=> false
"This".downcase?  #=> false
"this".downcase?  #=> true

CREDIT: Phil Tomson

Returns:

  • (Boolean)


23
24
25
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/capitalized.rb', line 23

def downcase?
  downcase == self
end

#dresnerObject

Scramble the inner characters of words leaving the text still readable (research at Cambridge University, code by KurtDresner).

For example, the above text may result in:

Srblamce the iennr cchrteaars of wodrs lvenaig the txet stlil rbeaadle
(rreceash at Cbamigdre Uverintisy, cdoe by KrneruestDr?)


37
38
39
# File 'lib/gems/english-0.3.1/lib/english/dresner.rb', line 37

def dresner
  English::Dresner.dresner(self)
end

#dresner!Object

Inplace version of #dresner method.



43
44
45
# File 'lib/gems/english-0.3.1/lib/english/dresner.rb', line 43

def dresner!
  replace(dresner)
end

#each_charObject

Yields a single-character string for each character in the string. When $KCODE = 'UTF8', multi-byte characters are yielded appropriately.



22
23
24
25
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/each_char.rb', line 22

def each_char
  scanner, char = StringScanner.new(self), /./mu
  loop { yield(scanner.scan(char) || break) }
end

#each_word(&block) ⇒ Object

Iterate through each word of a string.

"a string".each_word { |word, range| ... }


9
10
11
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/each_word.rb', line 9

def each_word(&block)
  words.each(&block)
end

#end_with?(suffix) ⇒ Boolean

Does a string end with the given suffix?

"hello".ends_with?("lo")    #=> true
"hello".ends_with?("to")    #=> false

CREDIT: Lucas Carlson CREDIT: Blaine Cook

Returns:

  • (Boolean)


25
26
27
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/start_with.rb', line 25

def end_with?(suffix)
  self.rindex(suffix) == size - suffix.size
end

#escape_regexpString

Returns The string with all regexp special characters escaped.

Examples:

"*?{}.".escape_regexp #=> "\\*\\?\\{\\}\\."

Returns:

  • (String)

    The string with all regexp special characters escaped.



9
10
11
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 9

def escape_regexp
  Regexp.escape self
end

#expand_tabs(n = 8) ⇒ Object

Expands tabs to n spaces. Non-destructive. If n is 0, then tabs are simply removed. Raises an exception if n is negative.

Thanks to GGaramuno for a more efficient algorithm. Very nice.

CREDIT: Gavin Sinclair CREDIT: Noah Gibbs CREDIT: GGaramuno

Raises:

  • (ArgumentError)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/tab.rb', line 26

def expand_tabs(n=8)
  n = n.to_int
  raise ArgumentError, "n must be >= 0" if n < 0
  return gsub(/\t/, "") if n == 0
  return gsub(/\t/, " ") if n == 1
  str = self.dup
  while
    str.gsub!(/^([^\t\n]*)(\t+)/) { |f|
      val = ( n * $2.size - ($1.size % n) )
      $1 << (' ' * val)
    }
  end
  str
end

#fold(ignore_indented = false) ⇒ Object

Returns a new string with all new lines removed from adjacent lines of text.

s = "This is\na test.\n\nIt clumps\nlines of text."
s.fold

produces

"This is a test.\n\nIt clumps lines of text. "

One arguable flaw with this, that might need a fix: if the given string ends in a newline, it is replaced with a single space.

CREDIT: Trans


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/fold.rb', line 19

def fold(ignore_indented=false)
  ns = ''
  i = 0
  br = self.scan(/(\n\s*\n|\Z)/m) do |m|
    b = $~.begin(1)
    e = $~.end(1)
    nl = $&
    tx = slice(i...b)
    if ignore_indented and slice(i...b) =~ /^[ ]+/
      ns << tx
    else
      ns << tx.gsub(/[ ]*\n+/,' ')
    end
    ns << nl
    i = e
  end
  ns
end

#hexdigestObject



102
103
104
# File 'lib/mack-facets/extensions/string.rb', line 102

def hexdigest
  Digest::SHA1.hexdigest(self)
end

#hexdigest!Object



106
107
108
# File 'lib/mack-facets/extensions/string.rb', line 106

def hexdigest!
  self.replace(self.hexdigest)
end

#html_filter(*opts) ⇒ Object



515
516
517
# File 'lib/gems/facets-2.4.5/lib/more/facets/htmlfilter.rb', line 515

def html_filter(*opts)
  HtmlFilter.new(*opts).filter(self)
end

#humanizeObject

Capitalizes the first word and turns underscores into spaces and strips _id. Like titleize, this is meant for creating pretty output.

Examples "employee_salary" #=> "Employee salary" "author_id" #=> "Author"



88
89
90
# File 'lib/mack-facets/extensions/string.rb', line 88

def humanize
  self.gsub(/_id$/, "").gsub(/_/, " ").capitalize
end

#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



60
61
62
63
64
65
66
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/tab.rb', line 60

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

#index_all(s, reuse = false) ⇒ Object

Like index but returns an array of all index locations. The reuse flag allows the trailing portion of a match to be reused for subsquent matches.

"abcabcabc".index_all('a')  #=> [0,3,6]

"bbb".index_all('bb', false)  #=> [0]
"bbb".index_all('bb', true)   #=> [0,1]

TODO: Culd probably be defined for Indexable in general too.


66
67
68
69
70
71
72
73
74
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/range.rb', line 66

def index_all(s, reuse=false)
  s = Regexp.new(Regexp.escape(s)) unless Regexp===s
  ia = []; i = 0
  while (i = index(s,i))
    ia << i
    i += (reuse ? 1 : $~[0].size)
  end
  ia
end

#is_roman_numeral?Boolean

Returns true iif the subject is a roman numeral.

Returns:

  • (Boolean)


157
158
159
# File 'lib/gems/english-0.3.1/lib/english/roman.rb', line 157

def is_roman_numeral?
  English::RomanNumerals.is_roman_numeral?(self)
end

#jumbleObject

Jumble string.



27
28
29
# File 'lib/gems/english-0.3.1/lib/english/jumble.rb', line 27

def jumble
  English::Jumble.jumble(self)
end

#jumble!Object

In-place version of #jumble.



33
34
35
# File 'lib/gems/english-0.3.1/lib/english/jumble.rb', line 33

def jumble!
  replace(jumble)
end

#lchomp(match) ⇒ Object

Left chomp.

"help".lchomp("h")  #=> "elp"
"help".lchomp("k")  #=> "help"

CREDIT: Trans


10
11
12
13
14
15
16
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/chomp.rb', line 10

def lchomp(match)
  if index(match) == 0
    self[match.size..-1]
  else
    self.dup
  end
end

#lchomp!(match) ⇒ Object

In-place left chomp.

"help".lchomp("h")  #=> "elp"
"help".lchomp("k")  #=> "help"

CREDIT: Trans


25
26
27
28
29
30
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/chomp.rb', line 25

def lchomp!(match)
  if index(match) == 0
    self[0...match.size] = ''
    self
  end
end

#line_wrap(width, tabs = 4) ⇒ Object

Line wrap at width.

puts "1234567890".line_wrap(5)

produces

12345
67890

CREDIT: Trans



14
15
16
17
18
19
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/line_wrap.rb', line 14

def line_wrap(width, tabs=4)
  s = gsub(/\t/,' ' * tabs) # tabs default to 4 spaces
  s = s.gsub(/\n/,' ')
  r = s.scan( /.{1,#{width}}/ )
  r.join("\n") << "\n"
end

#linesObject

Returns an array of characters.

"abc\n123".lines  #=> ["abc","123"]


9
10
11
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/lines.rb', line 9

def lines
  self.split(/\n/)
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



111
112
113
114
115
116
117
118
119
120
121
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 111

def margin(indicator = nil)
  lines = self.dup.split($/)

  min_margin = 0
  lines.each do |line|
    if line =~ /^(\s+)/ && (min_margin == 0 || $1.size < min_margin)
      min_margin = $1.size
    end
  end
  lines.map { |line| line.sub(/^\s{#{min_margin}}/, '') }.join($/)
end

#metaphoneObject

Returns the Metaphone representation of a string.



106
107
108
# File 'lib/gems/english-0.3.1/lib/english/metaphone.rb', line 106

def metaphone
  English::Metaphone.metaphone(self)
end

#methodizeObject

Translate a (class or module) name to a suitable method name.

My::CoolClass.name.methodize => "my__cool_class"


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/methodize.rb', line 7

def methodize
  x = self
  
  # if we get down to a nil or an empty string raise an exception! 
  raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  
  # get rid of the big stuff in the front/back
  x.strip!
  
  # if we get down to a nil or an empty string raise an exception! 
  raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  
  x = x.underscore
  
  # get rid of spaces and make the _
  x.gsub!(' ', '_')
  # get rid of everything that isn't 'safe' a-z, 0-9, ?, !, =, _
  x.gsub!(/([^ a-zA-Z0-9\_\?\!\=]+)/n, '_')
  
  # if we get down to a nil or an empty string raise an exception! 
  raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  
  # condense multiple 'safe' non a-z chars to just one.
  # ie. ___ becomes _ !!!! becomes ! etc...
  [' ', '_', '?', '!', "="].each do |c|
    x.squeeze!(c)
  end
  
  # if we get down to a nil or an empty string raise an exception! 
  raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  
  #down case the whole thing
  x.downcase!
  
  # get rid of any characters at the beginning that aren't a-z
  while !x.match(/^[a-z]/)
    x.slice!(0)
    
    # if we get down to a nil or an empty string raise an exception! 
    raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  end
  
  # let's trim this bad boy down a bit now that we've cleaned it up, somewhat.
  # we should do this before cleaning up the end character, because it's possible to end up with a 
  # bad char at the end if you trim too late.
  x = x[0..100] if x.length > 100
  
  # get rid of any characters at the end that aren't safe
  while !x.match(/[a-z0-9\?\!\=]$/)
    x.slice!(x.length - 1)
    # if we get down to a nil or an empty string raise an exception! 
    raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  end
  
  # if we get down to a nil or an empty string raise an exception! 
  raise NameError.new("#{self} cannot be converted to a valid method name!") if x.nil? || x == ''
  
  # let's get rid of characters that don't belong in the 'middle' of the method.
  orig_middle = x[1..(x.length - 2)]
  n_middle = orig_middle.dup
  
  ['?', '!', "="].each do |c|
    n_middle.gsub!(c, "_")
  end
  
  # the previous gsub can leave us with multiple underscores that need cleaning up.
  n_middle.squeeze!("_")
  
  x.gsub!(orig_middle, n_middle)
  x.gsub!("_=", "=")
  x
end

#modulizeObject

Converts a string to module name representation.

This is essentially #camelcase. It also converts '/' to '::' which is useful for converting paths to namespaces.

Examples "method_name".modulize #=> "MethodName" "method/name".modulize #=> "Method::Name"



13
14
15
16
17
18
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/modulize.rb', line 13

def modulize
  gsub('__','/').
  gsub(/\/(.?)/){ "::#{$1.upcase}" }.
  gsub(/(?:_+|-+)([a-z])/){ $1.upcase }.
  gsub(/(\A|\s)([a-z])/){ $1 + $2.upcase }
end

#mscan(re) ⇒ Object

Like #scan but returns MatchData ($~) rather then matched string ($&).

CREDIT: Trans


8
9
10
11
12
13
14
15
16
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/mscan.rb', line 8

def mscan(re) #:yield:
  if block_given?
    scan(re) { yield($~) }
  else
    m = []
    scan(re) { m << $~ }
    m
  end
end

#natcmp(str2, caseInsensitive = false) ⇒ Object

'Natural order' comparison of strings, e.g.

"my_prog_v1.1.0" < "my_prog_v1.2.0" < "my_prog_v1.10.0"

which does not follow alphabetically. A secondary parameter, if set to true, makes the comparison case insensitive.

"Hello.10".natcmp("Hello.1")  #=> -1

TODO: Invert case flag?

CREDIT: Alan Davies
CREDIT: Martin Pool

-- Adapted from:

http://sourcefrog.net/projects/natsort/natcmp.rb

Based on Martin Pool's "Natural Order String Comparison" originally written in C. (see http://sourcefrog.net/projects/natsort/)

This implementation is Copyright (C) 2003 by Alan Davies <cs96and_AT_yahoo_DOT_co_DOT_uk>

This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  3. This notice may not be removed or altered from any source distribution.

++



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/natcmp.rb', line 47

def natcmp(str2, caseInsensitive=false)
  str1 = self.dup
  str2 = str2.dup
  compareExpression = /^(\D*)(\d*)(.*)$/

  if caseInsensitive
    str1.downcase!
    str2.downcase!
  end

  # remove all whitespace
  str1.gsub!(/\s*/, '')
  str2.gsub!(/\s*/, '')

  while (str1.length > 0) or (str2.length > 0) do
    # Extract non-digits, digits and rest of string
    str1 =~ compareExpression
    chars1, num1, str1 = $1.dup, $2.dup, $3.dup
    str2 =~ compareExpression
    chars2, num2, str2 = $1.dup, $2.dup, $3.dup
    # Compare the non-digits
    case (chars1 <=> chars2)
      when 0 # Non-digits are the same, compare the digits...
        # If either number begins with a zero, then compare alphabetically,
        # otherwise compare numerically
        if (num1[0] != 48) and (num2[0] != 48)
          num1, num2 = num1.to_i, num2.to_i
        end
        case (num1 <=> num2)
          when -1 then return -1
          when 1 then return 1
        end
      when -1 then return -1
      when 1 then return 1
    end # case
  end # while

  # strings are naturally equal.
  return 0
end

#nchar(n, replacement = nil) ⇒ Object

Returns n characters of the string. If n is positive the characters are from the beginning of the string. If n is negative from the end of the string.

Alternatively a replacement string can be given, which will replace the n characters.

str = "this is text"
str.nchar(4)            #=> "this"
str.nchar(4, 'that')    #=> "that"
str                     #=> "that is text"

CREDIT: ?


17
18
19
20
21
22
23
24
25
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/nchar.rb', line 17

def nchar(n, replacement=nil)
  if replacement
    s = self.dup
    n > 0 ? (s[0...n] = replacement) : (s[n..-1] = replacement)
    return s
  else
    n > 0 ? self[0...n] : self[n..-1]
  end
end

#outdent(n) ⇒ Object

Outdent just indents a negative number of spaces.

CREDIT: Noah Gibbs



72
73
74
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/tab.rb', line 72

def outdent(n)
  indent(-n)
end

#pathizeObject

Converts a (class or module) name to a unix path.

My::CoolClass.name.pathize  #=> "my/cool_class"


7
8
9
10
11
12
13
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/pathize.rb', line 7

def pathize
  gsub(/([A-Z]+)([A-Z])/,'\1_\2').
  gsub(/([a-z])([A-Z])/,'\1_\2').
  gsub('__','/').
  gsub('::','/').
  downcase
end

#pluralObject Also known as: pluralize



295
296
297
# File 'lib/gems/english-0.3.1/lib/english/inflect.rb', line 295

def plural
  English::Inflect.plural(self)
end

#quote(type = :s) ⇒ Object

Return a new string embraced by given quotes. If no quotes are specified, then assumes single quotes.

"quote me".quote     #=> "'quote me'"
"quote me".quote(2)  #=> "\"quote me\""

CREDIT: Trans


69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/bracket.rb', line 69

def quote(type=:s)
  case type.to_s.downcase
  when 's', 'single'
    bracket("'")
  when 'd', 'double'
    bracket('"')
  when 'b', 'back'
    bracket('`')
  else
    bracket("'")
  end
end

#range(s, offset = 0) ⇒ Object

Like #index but returns a Range.

"This is a test!".range('test')  #=> 10..13

CREDIT: Trans


9
10
11
12
13
14
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/range.rb', line 9

def range(s, offset=0)
  if index(s, offset)
    return ($~.begin(0))..($~.end(0)-1)
  end
  nil
end

#range_all(s, reuse = false) ⇒ Object

Like #index_all but returns an array of Ranges.

"abc123abc123".range_all('abc')  #=> [0..2, 6..8]

TODO: Add offset, perhaps ?

CREDIT: Trans


24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/range.rb', line 24

def range_all(s, reuse=false)
  r = []; i = 0
  while i < self.length
    rng = range(s, i)
    if rng
      r << rng
      i += reuse ? 1 : rng.end + 1
    else
      break
    end
  end
  r.uniq
end

#range_of_lineObject

Returns an array of ranges mapping the characters per line.

"this\nis\na\ntest".range_of_line
#=> [0..4, 5..7, 8..9, 10..13]

CREDIT: Trans


46
47
48
49
50
51
52
53
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/range.rb', line 46

def range_of_line
  offset=0; charmap = []
  self.each do |line|
    charmap << (offset..(offset + line.length - 1))
    offset += line.length
  end
  charmap
end

#relative_path_from(other) ⇒ String

Returns Relative path from between the two.

Examples:

"/opt/local/lib".relative_path_from("/opt/local/lib/ruby/site_ruby") # => "../.."

Parameters:

  • other (String)

    Base path to calculate against

Returns:

  • (String)

    Relative path from between the two



85
86
87
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 85

def relative_path_from(other)
  Pathname.new(self).relative_path_from(Pathname.new(other)).to_s
end

#restore_snapshot(snap) ⇒ Object



190
# File 'lib/gems/facets-2.4.5/lib/more/facets/snapshot.rb', line 190

def restore_snapshot(snap) replace(snap) end

#shatter(re) ⇒ Object

Breaks a string up into an array based on a regular expression. Similar to scan, but includes the matches.

s = "<p>This<b>is</b>a test.</p>"
s.shatter( /\<.*?\>/ )

produces

["<p>", "This", "<b>", "is", "</b>", "a test.", "</p>"]

CREDIT: Trans


15
16
17
18
19
20
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/shatter.rb', line 15

def shatter( re )
  r = self.gsub( re ){ |s| "\1" + s + "\1" }
  while r[0,1] == "\1" ; r[0] = '' ; end
  while r[-1,1] == "\1" ; r[-1] = '' ; end
  r.split("\1")
end

#similarity(str_in) ⇒ Object Also known as: fuzzy_match

A fuzzy matching mechanism. Returns a score from 0-1, based on the number of shared edges. To be effective, the strings must be of length 2 or greater.

"Alexsander".fuzzy_match( "Aleksander" )  #=> 0.9

The way it works:

  • Converts each string into a "graph like" object, with edges "alexsander" -> [ alexsander, alexsand, alexsan ... lexsand ... san ... an, etc ] "aleksander" -> [ aleksander, aleksand ... etc. ]
  • Perform match, then remove any subsets from this matched set (i.e. a hit on "san" is a subset of a hit on "sander") Above example, once reduced -> [ ale, sander ]
  • See's how many of the matches remain, and calculates a score based on how many matches, their length, and compare to the length of the larger of the two words.

-- Credit goes to Derek Lewis. Thanks Derek! Still a bit rough. Any suggestions for improvement are welcome. ++



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/gems/english-0.3.1/lib/english/similarity.rb', line 41

def similarity( str_in )
  return 0 if str_in == nil
  return 1 if self == str_in

  # Make a graph of each word (okay, so its not a true graph, but is similar)
  graph_A = Array.new
  graph_B = Array.new

  # "graph" self
  last = self.length
  (0..last).each do |ff|
    loc  = self.length
    break if ff == last - 1
    wordB = (1..(last-1)).to_a.reverse!
    if (wordB != nil)
      wordB.each do |ss|
        break if ss == ff
        graph_A.push( "#{self[ff..ss]}" )
      end
    end
  end

  # "graph" input string
  last = str_in.length
  (0..last).each{ |ff|
    loc  = str_in.length
    break if ff == last - 1
    wordB = (1..(last-1)).to_a.reverse!
    wordB.each do |ss|
      break if ss == ff
      graph_B.push( "#{str_in[ff..ss]}" )
    end
  }

  # count how many of these "graph edges" we have that are the same
  matches = graph_A & graph_B
  #matches = Array.new
  #graph_A.each do |aa|
  #  matches.push( aa ) if( graph_B.include?( aa ) )
  #end

  # For eliminating subsets, we want to start with the smallest hits.
  matches.sort!{|x,y| x.length <=> y.length}

  # eliminate any subsets
  mclone = matches.dup
  mclone.each_index do |ii|
    reg = Regexp.compile( Regexp.escape(mclone[ii]) )
    count = 0.0
    matches.each{|xx| count += 1 if xx =~ reg}
    matches.delete(mclone[ii]) if count > 1
  end

  score = 0.0
  matches.each{ |mm| score += mm.length }
  self.length > str_in.length ? largest = self.length : largest = str_in.length
  return score/largest
end

#singularObject Also known as: singularize



290
291
292
# File 'lib/gems/english-0.3.1/lib/english/inflect.rb', line 290

def singular
  English::Inflect.singular(self)
end

#snake_caseString

Returns The string converted to snake case.

Examples:

"FooBar".snake_case #=> "foo_bar"
"HeadlineCNNNews".snake_case #=> "headline_cnn_news"
"CNN".snake_case #=> "cnn"

Returns:

  • (String)

    The string converted to snake case.



31
32
33
34
35
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 31

def snake_case
  return self.downcase if self =~ /^[A-Z]+$/
  self.gsub(/([A-Z]+)(?=[A-Z][a-z]?)|\B[A-Z]/, '_\&') =~ /_*(.*)/
    return $+.downcase
end

#snakecaseObject

The reverse of camelcase. Makes an underscored of a camelcase string.

Changes '::' to '/' to convert namespaces to paths.

Examples "SnakeCase".snakecase #=> "snake_case" "Snake-Case".snakecase #=> "snake_case" "SnakeCase::Errors".underscore #=> "snake_case/errors"



12
13
14
15
16
17
18
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/snakecase.rb', line 12

def snakecase
  gsub(/::/, '/').  # NOT SO SURE ABOUT THIS -T
  gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
  gsub(/([a-z\d])([A-Z])/,'\1_\2').
  tr("-", "_").
  downcase
end

#soundexObject



66
67
68
# File 'lib/gems/english-0.3.1/lib/english/soundex.rb', line 66

def soundex
  English::Soundex.soundex(self)
end

#splice(idx, sub = nil) ⇒ Object

This is basically the same as #store, but it acts like slice! when given only one argument.

Essentlay #slice, but writes rather than reads.

a = "HELLO"
a.splice("X", 1)
a                #=> "HXLLO"

a = "HELLO"
a.splice(1)    #=> "E"
a              #=> "HLLO"

CREDIT: Trans


20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/splice.rb', line 20

def splice(idx, sub=nil)
  if sub
    store(idx, sub)
  else
    case idx
    when Range
      slice!(idx) 
    else
      slice!(idx,1)
    end
  end
end

#start_with?(prefix) ⇒ Boolean

Does a string start with the given prefix.

"hello".starts_with?("he")    #=> true
"hello".starts_with?("to")    #=> false

CREDIT: Lucas Carlson CREDIT: Blaine Cook

Returns:

  • (Boolean)


13
14
15
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/start_with.rb', line 13

def start_with?(prefix)
  self.index(prefix) == 0
end

#succ(n = 1) ⇒ Object

Allows #succ to take n step increments.

"abc".succ      #=> "abd"
"abc".succ(4)   #=> "abg"
"abc".succ(24)  #=> "aca"

CREDIT Trans



37
38
39
40
41
# File 'lib/gems/facets-2.4.5/lib/more/facets/succ.rb', line 37

def succ(n=1)
  s = self
  n.times { s = s.succ1 }
  s
end

#succ1Object



27
# File 'lib/gems/facets-2.4.5/lib/more/facets/succ.rb', line 27

alias_method :succ1, :succ

#t(*values) ⇒ Object

values using numeric identifier replacement.

"%s %s %s" % %w(one two three) #=> "one two three" "%3$s %2$s %1$s" % %w(one two three) #=> "three two one"



129
130
131
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 129

def t(*values)
  self.class::translate(self) % values.collect! { |value| value.frozen? ? value : self.class::translate(value.to_s) }
end

#tab(n) ⇒ Object Also known as: taballto

Aligns each line n spaces.

CREDIT: Gavin Sinclair



10
11
12
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/tab.rb', line 10

def tab(n)
  gsub(/^ */, ' ' * n)
end

#tabto(n) ⇒ Object

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

CREDIT: Gavin Sinclair



46
47
48
49
50
51
52
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/tab.rb', line 46

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

#take_snapshotObject



189
# File 'lib/gems/facets-2.4.5/lib/more/facets/snapshot.rb', line 189

def take_snapshot() dup end

#titlecaseObject

Title case.

"this is a string".titlecase
=> "This Is A String"

CREDIT: Eliazar Parra



10
11
12
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/titlecase.rb', line 10

def titlecase
  gsub(/\b\w/){$&.upcase}
end

#to_bObject

Interpret common affirmative string meanings as true, otherwise false. Balnk sapce and case are ignored. The following strings that will return true:

<tt>true</tt>,<tt>yes</tt>,<tt>on</tt>,<tt>t</tt>,<tt>1</tt>,<tt>y</tt>,<tt>==</tt>

Examples:

"true".to_b   #=> true
"yes".to_b    #=> true
"no".to_b     #=> false
"123".to_b    #=> false


43
44
45
46
47
48
49
50
51
52
# File 'lib/gems/facets-2.4.5/lib/core/facets/boolean.rb', line 43

def to_b
  case self.downcase.strip
  when 'true', 'yes', 'on', 't', '1', 'y', '=='
    return true
  when 'nil', 'null'
    return nil
  else
    return false
  end
end

#to_const_pathString

Returns The path that is associated with the constantized string, assuming a conventional structure.

Examples:

"FooBar::Baz".to_const_path # => "foo_bar/baz"

Returns:

  • (String)

    The path that is associated with the constantized string, assuming a conventional structure.



63
64
65
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 63

def to_const_path
  snake_case.gsub(/::/, "/")
end

#to_const_stringString

Returns The path string converted to a constant name.

Examples:

"merb/core_ext/string".to_const_string #=> "Merb::CoreExt::String"

Returns:

  • (String)

    The path string converted to a constant name.



52
53
54
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 52

def to_const_string
  gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
end

#to_dateObject

Parse data from string.



390
391
392
393
# File 'lib/gems/facets-2.4.5/lib/lore/facets/date.rb', line 390

def to_date
  #::Date::civil(*ParseDate.parsedate(self)[0..2])
  ::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday))
end

#to_datetimeObject

Convert string to DateTime.



384
385
386
387
# File 'lib/gems/facets-2.4.5/lib/lore/facets/date.rb', line 384

def to_datetime
  date = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec).map { |arg| arg || 0 }
  ::DateTime.civil(*date)
end

#to_i_romanObject

Considers string a roman numeral numeral, and converts it to the corresponding integer.



151
152
153
# File 'lib/gems/english-0.3.1/lib/english/roman.rb', line 151

def to_i_roman
  English::RomanNumerals.to_integer(self)
end

#to_mask(re = nil) ⇒ Object

Create a mask.



6
7
8
# File 'lib/gems/facets-2.4.5/lib/more/facets/string/mask.rb', line 6

def to_mask(re=nil)
  Mask.new(self,re)
end

#to_re(esc = false) ⇒ Object

Turns a string into a regular expression.

"a?".to_re  #=> /a?/

CREDIT: Trans



9
10
11
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/to_re.rb', line 9

def to_re(esc=false)
  Regexp.new((esc ? Regexp.escape(self) : self))
end

#to_rx(esc = true) ⇒ Object

Turns a string into a regular expression. By default it will escape all characters. Use false argument to turn off escaping.

"[".to_rx  #=> /\[/

CREDIT: Trans



21
22
23
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/to_re.rb', line 21

def to_rx(esc=true)
  Regexp.new((esc ? Regexp.escape(self) : self))
end

#to_sObject



2
3
4
# File 'lib/gems/facets-2.4.5/lib/core/facets/comparable/bound.rb', line 2

def to_s
  self
end

#to_t(&yld) ⇒ Object

Translates a string in the form on a set of numerical and/or alphanumerical characters separated by non-word characters (eg \W+) into a Tuple. The values of the tuple will be converted to integers if they are purely numerical.

'1.2.3a'.to_t  #=> [1,2,"3a"]

It you would like to control the interpretation of each value as it is added to the tuple you can supply a block.

'1.2.3a'.to_t { |v| v.upcase }  #=> ["1","2","3A"]

This method calls Tuple.cast_from_string.



309
310
311
# File 'lib/gems/facets-2.4.5/lib/more/facets/tuple.rb', line 309

def to_t( &yld )
  Tuple.cast_from_string( self, &yld )
end

#truncate(length = 30, truncate_string = "...") ⇒ Object



133
134
135
136
137
138
139
140
141
142
# File 'lib/mack-facets/extensions/string.rb', line 133

def truncate(length = 30, truncate_string = "...")
  if self.nil? then return end
  l = length - truncate_string.length
  if $KCODE == "NONE"
    self.length > length ? self[0...l] + truncate_string : self
  else
    chars = self.split(//)
    chars.length > length ? chars[0...l].join + truncate_string : self
  end
end

#truncate!(length = 30, truncate_string = "...") ⇒ Object



144
145
146
# File 'lib/mack-facets/extensions/string.rb', line 144

def truncate!(length = 30, truncate_string = "...")
  self.replace(self.truncate(length, truncate_string))
end

#unbracket(bra = nil, ket = nil) ⇒ Object

Return a new string embraced by given brakets. If only one bracket char is given it will be placed on either side.

"{unwrap me}".debracket('{')        #=> "unwrap me"
"--unwrap me!".debracket('--','!')  #=> "unwrap me!"

CREDIT: Trans


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/bracket.rb', line 37

def unbracket(bra=nil, ket=nil)
  if bra
    ket = BRA2KET[bra] unless ket
    ket = ket ? ket : bra
    s = self.dup
    s.gsub!(%r[^#{Regexp.escape(bra)}], '')
    s.gsub!(%r[#{Regexp.escape(ket)}$], '')
    return s
  else
    if m = BRA2KET[ self[0,1] ]
      return self.slice(1...-1) if self[-1,1]  == m
    end
  end
  return self.dup  # if nothing else
end

#unbracket!(bra = nil, ket = nil) ⇒ Object

Inplace version of #debraket.

CREDIT: Trans


57
58
59
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/bracket.rb', line 57

def unbracket!(bra=nil, ket=nil)
  self.replace( unbracket(bra, ket) )
end

#unescape_regexpObject

Returns String The string with all regexp special characters unescaped.

Examples:

"\\*\\?\\{\\}\\.".unescape_regexp #=> "*?{}."

Returns:

  • String The string with all regexp special characters unescaped.



18
19
20
# File 'lib/gems/extlib-0.9.8/lib/extlib/string.rb', line 18

def unescape_regexp
  self.gsub(/\\([\.\?\|\(\)\[\]\{\}\^\$\*\+\-])/, '\1')
end

#upcase?Boolean

Is the string upcase/uppercase?

"THIS".upcase?  #=> true
"This".upcase?  #=> false
"this".upcase?  #=> false

CREDIT: Phil Tomson

Returns:

  • (Boolean)


38
39
40
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/capitalized.rb', line 38

def upcase?
  upcase == self
end

#uri_escapeObject

Performs URI escaping so that you can construct proper query strings faster. Use this rather than the cgi.rb version since it's faster. (Stolen from Camping).



120
121
122
123
124
# File 'lib/mack-facets/extensions/string.rb', line 120

def uri_escape
  self.gsub(/([^ a-zA-Z0-9_.-]+)/n) {
    '%'+$1.unpack('H2'*$1.size).join('%').upcase
  }.tr(' ', '+')
end

#uri_unescapeObject

Unescapes a URI escaped string. (Stolen from Camping).



127
128
129
130
131
# File 'lib/mack-facets/extensions/string.rb', line 127

def uri_unescape
  self.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n){
    [$1.delete('%')].pack('H*')
  }
end

#variablizeObject

Prepend an "@" to the beginning of a string to make a instance variable name. This also replaces non-valid characters with underscores.



7
8
9
10
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/variablize.rb', line 7

def variablize
  v = gsub(/\W/, '_')
  "@#{v}"
end

#word_wrap(col_width = 80) ⇒ Object

Word wrap a string not exceeding max width.

puts "this is a test".word_wrap(4)

produces

this
is a
test

This is basic implementation of word wrap, but smart enough to suffice for most use cases.

CREDIT: Gavin Kistner CREDIT: Dayne Broderson



19
20
21
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/word_wrap.rb', line 19

def word_wrap( col_width=80 )
  self.dup.word_wrap!( col_width )
end

#word_wrap!(col_width = 80) ⇒ Object

As with #word_wrap, but modifies the string in place.

CREDIT: Gavin Kistner
CREDIT: Dayne Broderson


28
29
30
31
32
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/word_wrap.rb', line 28

def word_wrap!( col_width=80 )
  self.gsub!( /(\S{#{col_width}})(?=\S)/, '\1 ' )
  self.gsub!( /(.{1,#{col_width}})(?:\s+|$)/, "\\1\n" )
  self
end

#wordsObject

Returns an array of characters.

"abc 123".words  #=> ["abc","123"]


7
8
9
# File 'lib/gems/facets-2.4.5/lib/core/facets/string/words.rb', line 7

def words
  self.split(/\s+/)
end