Methods
Included Modules
Classes and Modules
Module String::Words
Constants
BRA2KET = { '['=>']', '('=>')', '{'=>'}', '<'=>'>' }
Public Class methods
interpolate(&str)

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
# File lib/facets/string/interpolate.rb, line 15
  def self.interpolate(&str)
    eval "%{#{str.call}}", str.binding
  end
Public Instance methods
-(pattern)

Removes occurances of a string or regexp.

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

  CREDIT: Benjamin David Oakes
# File lib/facets/string/subtract.rb, line 9
  def -(pattern)
    self.gsub(pattern, '')
  end
^(aString)

XOR two string.

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

# File lib/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=' ')
# File lib/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=' ')

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 = <<-EOS
    This is a test
    and
    so on
  EOS

  puts s.align_center(14)

produces

  This is a test
       and
      so on

  CREDIT: Trans
# File lib/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=' ')

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 = <<-EOS
  This is a test
    and
    so on
  EOS

  puts s.align_left(2)

produces

    This is a test
    and
    so on

  CREDIT: Trans
# File lib/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=' ')

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 = <<-EOS
  This is a test
    and
    so on
  EOS

  puts s.align_right(2)

produces

    This is a test
               and
             so on

  CREDIT: Trans
# File lib/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?()

Is this string just whitespace?

  "abc".blank?  #=> false
  "   ".blank?  #=> true
# File lib/facets/blank.rb, line 50
  def blank?
    self !~ /\S/
  end
bracket(bra, ket=nil)

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
# File lib/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)

Inplace version of braket.

  CREDIT: Trans
# File lib/facets/string/bracket.rb, line 24
  def bracket!(bra, ket=nil)
    self.replace(bracket(bra, ket))
  end
bytes()

Upacks string into bytes.

# File lib/facets/ruby.rb, line 336
    def bytes
      self.unpack('C*')
    end
camelcase(upcase_first_letter=true)

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"
# File lib/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?()

Return true if the string is capitalized, otherwise false.

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

 CREDIT: Phil Tomson
# File lib/facets/string/capitalized.rb, line 11
  def capitalized?
    self =~ /^[A-Z]/
  end
chars()

Returns an array of characters.

  "abc".chars  #=> ["a","b","c"]
# File lib/facets/ruby.rb, line 344
    def chars
      self.split(//)
    end
cleave(threshold=nil, len=nil)

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

 CREDIT: Trans
# File lib/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)

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
# File lib/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
dequote()

Remove quotes from string.

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

  CREDIT: Trans
# File lib/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 )

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
# File lib/facets/string/divide.rb, line 15
  def divide( re )
    re2 = /#{re}.*?(?=#{re}|\Z)/
    scan(re2) #{re}(?=#{re})/)
  end
downcase?()

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

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

 CREDIT: Phil Tomson
# File lib/facets/string/capitalized.rb, line 23
  def downcase?
    downcase == self
  end
each_char( {|| ...}

Iterates through each character. This is a little faster than using chars b/c it does not create the intermediate array.

   a = ''
  "HELLO".each_character{ |c| a << #{c.downcase} }
   a  #=> 'hello'
# File lib/facets/ruby.rb, line 363
    def each_char  # :yield:
      size.times do |i|
        yield(self[i,1])
      end
    end
end_with?(suffix)

Does a string end with the given suffix?

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

 CREDIT: Lucas Carlson
 CREDIT: Blaine Cook
# File lib/facets/ruby.rb, line 389
    def end_with?(suffix)
      self.rindex(suffix) == size - suffix.size
    end
expand_tabs(n=8)

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
# File lib/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)

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
# File lib/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
humanize()

Replaces underscores with spaces and capitalizes word.

# File lib/facets/string/stylize.rb, line 59
  def humanize
    self.gsub(/_/, " ").capitalize
  end
indent(n)

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

 CREDIT: Gavin Sinclair
 CREDIT: Trans
# File lib/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)

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.
# File lib/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
lchomp(match)

Left chomp.

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

  CREDIT: Trans
# File lib/facets/string/chomp.rb, line 10
  def lchomp(match)
    if index(match) == 0
      self[match.size..-1]
    else
      self.dup
    end
  end
lchomp!(match)

In-place left chomp.

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

  CREDIT: Trans
# File lib/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)

Line wrap at width.

  puts "1234567890".line_wrap(5)

produces

  12345
  67890

 CREDIT: Trans
# File lib/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
lines()

Returns an array of characters.

  "abc\n123".lines  #=> ["abc","123"]
# File lib/facets/ruby.rb, line 352
    def lines
      self.split(/\n/)
    end
margin(n=0)

Provides a margin controlled string.

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

  NOTE: This may still need a bit of tweaking.

 CREDIT: Trans
# File lib/facets/string/tab.rb, line 89
  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
methodize()

Just like snakecase. Makes an underscored form from the expression in the string, but also changes ’::’ to ’/’ to convert namespaces to paths.

Examples

  "SuperMan".methodize         #=> "super_man"
  "SuperMan::Errors".methodize #=> "super_man__errors
# File lib/facets/string/stylize.rb, line 48
  def methodize
    gsub(/\//, '__').
    gsub(/::/, '__').
    gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    tr("-", "_").
    downcase
  end
modulize()

Like camelcase, but also converts ’/’ to ’::’.

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".modulize                    #=> "CamelCase"
  "camel/case".modulize                    #=> "Camel::Case"
# File lib/facets/string/stylize.rb, line 15
  def modulize
    str = dup
    str.gsub!(/__(.?)/){ "::#{$1.upcase}" }
    str.gsub!(/\/(.?)/){ "::#{$1.upcase}" }
    str.gsub!(/(?:_+)([a-z])/){ $1.upcase }
    str.gsub!(/(^|\s+)([a-z])/){ $1 + $2.upcase }
    str
  end
mscan(re) {|| ...}

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

  CREDIT: Trans
# File lib/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)

‘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
# File lib/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

end
nchar(n, replacement=nil)

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: ?
# File lib/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)

Outdent just indents a negative number of spaces.

 CREDIT: Noah Gibbs
# File lib/facets/string/tab.rb, line 72
  def outdent(n)
    indent(-n)
  end
pathize()

Just like snakecase. Makes an underscored form from the expression in the string, but also changes ’::’ to ’/’ to convert namespaces to paths.

Examples

  "SuperMan".pathize           #=> "super_man"
  "SuperMan::Errors".pathize   #=> "super_man/errors
# File lib/facets/string/stylize.rb, line 32
  def pathize
    gsub(/::/, '/').
    gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    tr("-", "_").
    downcase
  end
quote(type=:s)

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
# File lib/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)

Like index but returns a Range.

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

  CREDIT: Trans
# File lib/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)

Like index_all but returns an array of Ranges.

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

  TODO: Add offset, perhaps ?

  CREDIT: Trans
# File lib/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_line()

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
# File lib/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
rewrite(rules)

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

Requirements:

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

Input:

The array containing rule-pairs (match, write).

Output:

The rewritten string.

  CREDIT: George Moschovitis
# File lib/facets/string/rewrite.rb, line 18
  def rewrite(rules)
    raise ArgumentError.new('The rules parameter is nil') unless rules
    rewritten_string = dup
    rules.each do |match,write|
      rewritten_string.gsub!(match,write)
    end
    return rewritten_string
  end
shatter( re )

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
# File lib/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
snakecase()

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"
# File lib/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
space()

Replaces underscores with spaces and capitalizes word.

# File lib/facets/string/underscore.rb, line 23
  def space
    gsub('_', ' ').capitalize
  end
splice(*args)

Like slice, but writes rather than reads. Like store, but acts like slice! when given only one argument.

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

  CREDIT: Trans
# File lib/facets/string/splice.rb, line 13
  def splice(*args)
    if args.size == 1
      slice!(*args)
    else
      store(*args)
    end
  end
start_with?(prefix)

Does a string start with the given prefix.

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

 CREDIT: Lucas Carlson
 CREDIT: Blaine Cook
# File lib/facets/ruby.rb, line 377
    def start_with?(prefix)
      self.index(prefix) == 0
    end
tab(n)

Aligns each line n spaces.

 CREDIT: Gavin Sinclair
This method is also aliased as taballto
# File lib/facets/string/tab.rb, line 10
  def tab(n)
    gsub(/^ */, ' ' * n)
  end
taballto(n)

Alias for tab

tabto(n)

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

 CREDIT: Gavin Sinclair
# File lib/facets/string/tab.rb, line 46
  def tabto(n)
    if self =~ /^( *)\S/
      indent(n - $1.length)
    else
      self
    end
  end
titlecase()

Title case.

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

 CREDIT: Eliazar Parra
# File lib/facets/string/titlecase.rb, line 10
  def titlecase
    gsub(/\b\w/){$&.upcase}
  end
titleize()

Titleize.

  "this is a string".titlecase
  => "This Is A String"
# File lib/facets/string/stylize.rb, line 68
  def titleize
    gsub(/\b\w/){$&.upcase}
  end
to_b()

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
# File lib/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_date()

Parse data from string.

 CREDIT: Trans
# File lib/facets/string/to_time.rb, line 16
  def to_date
    require 'date'
    require 'parsedate'
    ::Date::civil(*ParseDate.parsedate(self)[0..2])
  end
to_re(esc=false)

Turns a string into a regular expression.

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

 CREDIT: Trans
# File lib/facets/string/to_re.rb, line 9
  def to_re(esc=false)
    Regexp.new((esc ? Regexp.escape(self) : self))
  end
to_rx(esc=true)

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
# File lib/facets/string/to_re.rb, line 21
  def to_rx(esc=true)
    Regexp.new((esc ? Regexp.escape(self) : self))
  end
to_s()
# File lib/facets/comparable/bound.rb, line 2
  def to_s
    self
  end
to_time()

Parse string to time.

 CREDIT: Trans
# File lib/facets/string/to_time.rb, line 7
  def to_time
    require 'time'
    Time.parse(self)
  end
unbracket(bra=nil, ket=nil)

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
# File lib/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)

Inplace version of debraket.

  CREDIT: Trans
# File lib/facets/string/bracket.rb, line 57
  def unbracket!(bra=nil, ket=nil)
    self.replace( unbracket(bra, ket) )
  end
underscore()

Converts spaces into underscores.

Examples

  "This Is Helpful".underscore  #=> "This_Is_Helpful"
# File lib/facets/string/underscore.rb, line 17
  def underscore
    gsub(' ', '_') #.capitalize
  end
upcase?()

Is the string upcase/uppercase?

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

 CREDIT: Phil Tomson
# File lib/facets/string/capitalized.rb, line 38
  def upcase?
    upcase == self
  end
variablize()

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

# File lib/facets/metaid.rb, line 128
  def variablize
    "@#{self}".gsub(/\W/, '_').to_sym
  end