Class | String

In:

lib/facets/more/tuple.rb
lib/facets/more/typecast.rb
lib/facets/more/json.rb
lib/facets/more/ormsupport.rb
lib/facets/more/snapshot.rb
lib/facets/more/htmlfilter.rb
lib/facets/core/kernel/to_data.rb
lib/facets/core/enumerable/entropy.rb
lib/facets/core/string/word_filter.rb
lib/facets/core/string/upcase.rb
lib/facets/core/string/align_center.rb
lib/facets/core/string/natcmp.rb
lib/facets/core/string/to_b.rb
lib/facets/core/string/soundex.rb
lib/facets/core/string/bytes.rb
lib/facets/core/string/ordinal.rb
lib/facets/core/string/format.rb
lib/facets/core/string/shuffle.rb
lib/facets/core/string/nchar.rb
lib/facets/core/string/divide.rb
lib/facets/core/string/pop.rb
lib/facets/core/string/mscan.rb
lib/facets/core/string/pot.rb
lib/facets/core/string/last.rb
lib/facets/core/string/at.rb
lib/facets/core/string/rand_index.rb
lib/facets/core/string/dequote.rb
lib/facets/core/string/regesc.rb
lib/facets/core/string/camelcase.rb
lib/facets/core/string/pull.rb
lib/facets/core/string/shift.rb
lib/facets/core/string/push.rb
lib/facets/core/string/similarity.rb
lib/facets/core/string/unbracket.rb
lib/facets/core/string/line_wrap.rb
lib/facets/core/string/humanize.rb
lib/facets/core/string/unshift.rb
lib/facets/core/string/indent.rb
lib/facets/core/string/to_a.rb
lib/facets/core/string/singular.rb
lib/facets/core/string/lowercase.rb
lib/facets/core/string/capitalize_all.rb
lib/facets/core/string/shell_escape.rb
lib/facets/core/string/first.rb
lib/facets/core/string/modulize.rb
lib/facets/core/string/to_const.rb
lib/facets/core/string/each_word.rb
lib/facets/core/string/words.rb
lib/facets/core/string/index_all.rb
lib/facets/core/string/chars.rb
lib/facets/core/string/last_char.rb
lib/facets/core/string/pathize.rb
lib/facets/core/string/to_proc.rb
lib/facets/core/string/shatter.rb
lib/facets/core/string/starts_with.rb
lib/facets/core/string/margin.rb
lib/facets/core/string/to_date.rb
lib/facets/core/string/unpack.rb
lib/facets/core/string/first_char.rb
lib/facets/core/string/fold.rb
lib/facets/core/string/blank.rb
lib/facets/core/string/methodize.rb
lib/facets/core/string/camelize.rb
lib/facets/core/string/whitespace.rb
lib/facets/core/string/quote.rb
lib/facets/core/string/to_time.rb
lib/facets/core/string/demodulize.rb
lib/facets/core/string/dresner.rb
lib/facets/core/string/unix_crypt.rb
lib/facets/core/string/word_wrap.rb
lib/facets/core/string/rand_byte.rb
lib/facets/core/string/to_re.rb
lib/facets/core/string/bracket.rb
lib/facets/core/string/cmp.rb
lib/facets/core/string/range_all.rb
lib/facets/core/string/range_of_line.rb
lib/facets/core/string/brief.rb
lib/facets/core/string/capitalized.rb
lib/facets/core/string/range.rb
lib/facets/core/string/each_char.rb
lib/facets/core/string/succ.rb
lib/facets/core/string/downcase.rb
lib/facets/core/string/at_rand.rb
lib/facets/core/string/underscore.rb
lib/facets/core/string/lines.rb
lib/facets/core/string/basename.rb
lib/facets/core/string/rewrite.rb
lib/facets/core/string/cleave.rb
lib/facets/core/string/self/rand_letter.rb
lib/facets/core/string/self/patterns.rb
lib/facets/core/string/self/interpolate.rb

Parent: | Object

### Methods

align_center align_left align_right at_rand at_rand! basename blank? bra2ket bracket bracket! brief bytes camelcase camelize capitalize_all capitalized? cast_from chars cleave cmp dequote divide downcase? dresner dresner! each_char each_word ends_with? entropy first first! first= first_char fold format format from_data fuzzy_match html_filter humanize indent index_all inflection_rule inflection_rules inflection_rules_by_plural inflection_rules_by_singular interpolate json_create last last! last= last_char line_wrap lines margin methodize modulize mscan natcmp nchar ordinal pathize patterns plural pluralize pop pot pull push quote rand_byte rand_byte! rand_index rand_letter random range range_all range_of_line regesc restore_snapshot rewrite shatter shell_escape shift shuffle shuffle! similarity singular singularize soundex soundex_code sprintf starts_with? succ tab tabto take_snapshot to_a to_b to_const to_data to_date to_json to_json_raw to_json_raw_object to_proc to_re to_rx to_t to_time unbracket unbracket! underscore unix_crypt unix_crypt! unpack unshift upcase? uppercase? whitespace? whitespace? word_filter word_filter! word_wrap word_wrap! words

### Included Modules

ORMSupport

### External Aliases

slice | -> | at
| Alias for slice which increases polymorphism with Array.
downcase? | -> | lowercase?
| Alias for downcase? method.
unpack | -> | unpack_from_orgin
basename | -> | demodulize
succ | -> | succ_once

### Public Class methods

bra2ket()
cast_from(object)
format(*args)
inflection_rule( *args )
inflection_rules()
inflection_rules_by_plural()
inflection_rules_by_singular()
interpolate(&str)
json_create(o)

Raw Strings are JSON Objects (the raw bytes are stored in an array for the key "raw"). The Ruby String can be created by this class method.

patterns( pattern )

Returns a Regexp pattern based on the given pattern string or symbolic name.

Recognized names are:

- :char
- :word
- :line

They are also recognizied in plural form.

rand_letter()

Module method to generate a random letter.

      String::Random.rand_letter  #=> "q"
      String::Random.rand_letter  #=> "r"
      String::Random.rand_letter  #=> "a"

random(max_length = 8, char_re = /[\w\d]/)

Returns a randomly generated string. One possible use is password initialization. Takes a max legnth of characters (default 8) and an optional valid char Regexp (default /\w\d/).

soundex_code(character)

Support function for String#soundex. Returns code for a single character.

sprintf(*args)

### Public Instance methods

align_center( n, sep="\n", c=' ' )

Centers each line of a string.

      s = <<-EOS
      This is a test
      and
      so on
      EOS
      puts s.align_center(14)

produces

      This is a test
           and
          so on

Align a string to the center. 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 (’ ’).

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 (’ ’).

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 (’ ’).

at_rand( separator=// )

Return a random separation of the string. Default separation is by charaacter.

      "Ruby rules".at_rand(' ')  #=> ["Ruby"]

at_rand!( separator=// )

Return a random separation while removing it from the string. Default separation is by character.

      s = "Ruby rules"
      s = at_rand!(' ')  #=> "Ruby"
      s                  #=> "rules"

basename()

Removes prepend module namespace.

      "Test::Unit".basename  #=> "Unit"

blank?()

Is this string just whitespace?

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

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!"

bracket!(bra, ket=nil)

Inplace version of braket.

brief(string, count = 128, force_cutoff = false, ellipsis="...")

Returns short abstract of long strings (first ‘count’ characters, chopped at the nearest word, appended by ’…’) force_cutoff: break forcibly at ‘count’ chars. Does not accept count < 2.

bytes()

Upacks string into bytes.

camelcase( first=false, on='_\s' )

Converts a string to camelcase. By default capitalization occurs on whitespace and underscores. By setting the first parameter to `true` the first character can also be captizlized. The second parameter can be assigned a valid Regualr Expression characeter set to determine which characters to match for capitalizing subsequent parts of the string.

      "this_is a test".camelcase             #=> "thisIsATest"
      "this_is a test".camelcase(true)       #=> "ThisIsATest"
      "this_is a test".camelcase(true, ' ')  #=> "This_isATest"

camelize()

Variation of coverting a string to camelcase. This is unlike camelcase in that it is geared toward code reflection use.

      "this/is_a_test".camelize  #=> This::IsATest

capitalize_all( pattern=$;, *limit )

Capitalize all words (or other patterned divisions) of a string.

      "this is a test".capitalize_all  #=> "This Is A Test"

capitalized?()

Return true if the string is capitalized, otherwise false.

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

chars()

Returns an array of characters.

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

cleave(threshold=nil, len=nil)
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

dequote()
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>"]

downcase?()

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

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

dresner()

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?)

dresner!()

Inplace version of dresner method.

each_char( {|| ...}

Iterates through each character.

each_word( &yld )

Iterate through each word of a string.

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

ends_with?(str)
entropy()
first(separator_pattern=//)

Returns the first separation of a string. Default seperation is by character.

      "Hello World".first       #=> "H"
      "Hello World".first(' ')  #=> "Hello"

first!(separator_pattern=//)

Removes the first separation from a string. Defualt separation is by characters.

      a = "Hello World"
      a.first!       #=> "H"
      a              #=> "ello World"

      a = "Hello World"
      a.first!(' ')  #=> "Hello"
      a              #=> "World"

first=( x )

Prepends to a string.

      "Hello World".first = "Hello,"  #=> "Hello, Hello World"

first_char(n=1)

Returns first n characters.

      "Hello World".first_char(3)  #=> "Hel"

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. "

format( *args )
from_data(snap)
fuzzy_match( str_in )

Alias for similarity

html_filter(*opts)
humanize()

Replaces underscores with spaces and capitalizes word.

indent(n)

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

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]

last(separator_pattern=//)

Returns the last separation of a string. Default separation is by character.

      "Hello World".last(' ')  #=> "World"

last!(separator_pattern=//)

Removes the last separation from a string. Default seperation is by characeter.

      a = "Hello World"
      a.last!       #=> "d"
      a             #=> "Hello Worl"

      a = "Hello World"
      a.last!(' ')  #=> "World"
      a             #=> "Hello"

last=(str)

Appends to a string.

      "Hello World".last = ", Bye."  #=>  "Hello World, Bye."

last_char(n=1)

Returns last n characters.

      "Hello World".last_char(3)  #=> "rld"

line_wrap(width)

Line wrap at width.

      puts "1234567890".line_wrap(5)

produces

      12345
      67890

lines()

Returns an array of characters.

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

margin(n=0)

Provides a margin controlled string.

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

methodize()

Converts a string into a valid ruby method name This method is geared toward code reflection.

      "MyModule::MyClass".methodize  #=> "my_module__my_class"

See also String#modulize, String#pathize

## TODO

- Make sure that all scenarios return a valid ruby class name
- Make sure it is revertible

modulize()

Converts a string into a valid ruby class or module name This method is geared toward code reflection.

      "my_module__my_path".modulize  #=> "MyModule::MyPath"

See also String#methodize, String#pathize

TODO

- Make sure that all scenarios return a valid ruby class name
- Make sure it is revertible

mscan(re) {|| ...}

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

natcmp(str2, caseInsensitive=false)

‘Natural order’ comparison of two 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

nchar( n, replacement=nil )

Retrns 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.

ordinal()
pathize()

Converts a string into a unix path. This method is geared toward code reflection.

See : String#modulize, String#methodize

      "MyModule::MyClass".pathize   #=> my_module/my_class
      "my_module__my_class".pathize #=> my_module/my_class

TODO :

- Make sure that all scenarios return a valid unix path
- Make sure it is revertible

plural()

Convert an English word from singular to plurel.

      "boy".plural     #=> boys
      "tomato".plural  #=> tomatoes

pluralize()

Alias for plural

pop()

Polymorphic with Array of characters.

pot( str=' ' )

Like push but works from the other end of the string.

pull()

Same as shift.

push(str=' ')

Polymorphic with Array of characters.

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\""

rand_byte()

Return a random byte of self.

      "Ruby rules".rand_byte  #=> 121

rand_byte!()

Destructive rand_byte. Delete a random byte of self and return it.

      s = "Ruby rules"
      s.rand_byte!      #=> 121
      s                 #=> "Rub rules"

rand_index()

Return a random string index.

      "Ruby rules".rand_index  #=> 3

range(s, offset=0)

Like index but returns a Range.

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

range_all(s, reuse=false)

Like index_all but returns an array of Ranges.

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

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]

regesc()

Escape string for Regexp use.

restore_snapshot(snap)
rewrite(string, 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.

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>"]

shell_escape()

Escape special characters used in most unix shells to use it, eg. with system().

shift()
shuffle(separator=//)

Return the string with seperated sections arranged in a random order. The default seperation is by character.

      "Ruby rules".shuffle  #=> "e lybRsuur"

shuffle!(separator=//)

In place version of shuffle.

similarity( str_in )

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.

singular()

Convert an English word from plurel to singular.

      "boys".singular      #=> boy
      "tomatoes".singular  #=> tomato

singularize()

Alias for singular

soundex()

Implementation of the soundex algorithm as described by Knuth in volume 3 of The Art of Computer Programming. Returns nil if the value couldn‘t be calculated b/c of empty-string or invalid character.

      "Ruby".soundex  #=> "R100"

starts_with?(str)
succ(n=1)

Allows succ to take n step increments.

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

tab(n)

Aligns each line n spaces. (This used to be taballto.)

tabto(n)

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

take_snapshot()
to_a(div=//,limit=0)

Essentially makes to_a an alias for split, with the excpetion that if no divider is given then the array is split on charaters, and NOT on the global input record divider ($/).

WARNING There is a slight chance of incompatability with other libraries which depend on spliting with $/ (although doing so is a very bad idea!).

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

to_const()

Get a constant by a given string name.

      "Class".to_const   #=> Class

Note this method is not as verstile as it should be, since it can not access contants relative to the current execution context. But without a binding_of_caller that does not seem possible.

to_data()
to_date()
to_json(*)

This string should be encoded with UTF-8 (if JSON unicode support is enabled). A call to this method returns a JSON string encoded with UTF16 big endian characters as \u????. If JSON.support_unicode? is false only control characters are encoded this way, all 8-bit bytes are just passed through.

to_json_raw(*args)

This method should be used, if you want to convert raw strings to JSON instead of UTF-8 strings, e. g. binary data (and JSON Unicode support is enabled).

to_json_raw_object()

This method creates a raw object, that can be nested into other data structures and will be unparsed as a raw string.

to_proc(context=nil)

Evaluates a String as a Proc.

      xyp = "|x,y| x + y".to_proc
      xyp.class      #=> Proc
      xyp.call(1,2)  #=> 3

to_re(esc=true)

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

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

to_rx()

Turns a string into a regular expression. Unlike to_re this will not escape characters.

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

to_t( &yld )

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.

to_time()
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!"

unbracket!(bra=nil, ket=nil)

Inplace version of debraket.

underscore(

Underscore string based on camelcase characteristics.

unix_crypt()

Common Unix cryptography method.

unix_crypt!()

Common Unix cryptography in-place method.

unpack(format, offset=nil)

Upack with offset. Extends unpack to allow a string to be unpacked starting at an offset position within it.

unshift( str=' ' )
upcase?()

Is the string upcase/uppercase?

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

uppercase?()

Alias for upcase?

whitespace?()

Alias for blank?

whitespace?()

Alias for blank?

word_filter( &blk )

Filters out words from a string based on block test.

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

word_filter!( {|| ...}

In place version of word_filter.

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

word_wrap( col_width=80 )

Word wrap a string not exceeding max width.

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

produces

      this
      is a
      test

word_wrap!( col_width=80 )

As with word_wrap, but modifies the string in place.

words()

Returns an array of characters.

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

[Validate]