1 2 3 4 5 6 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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
|
require 'facets/string/splice'
require 'facets/string/scan'
require 'facets/indexable'
class String
include Indexable
# An extraneous feature, but make String more ploymorphic
# with Array.
#
# "HELLO".at(2) #=> "L"
def at(index)
case index
when Fixnum
self[index].chr
else
self[index]
end
end
#Or should this be like #split? or self + '/' + other?
#alias / []
#-----------------------------------------------------------------
# The following methods override Indexable to better suit String.
#-----------------------------------------------------------------
# Returns the first separation of a string.
# Default seperation is by character.
#
# "Hello World".first #=> "H"
# "Hello World".first(' ') #=> "Hello"
#
def first(pattern=//)
case pattern
when Regexp, String
split(pattern).at(0)
else
super
end
end
# Returns the last separation of a string.
# Default separation is by character.
#
# "Hello World".last(' ') #=> "World"
#
def last(pattern=//)
case pattern
when Regexp, String
split(pattern).at(-1)
else
super
end
end
# Removes the first separation from a string.
# Defualt separation is by characters.
#--
# If a zero-length record separator is supplied,
# the string is split on /\n+/. If the record
# separator is set to <tt>nil</tt>, then the
# string is split on characters.
#++
#
# a = "Hello World"
# a.first! #=> "H"
# a #=> "ello World"
#
# a = "Hello World"
# a.first!(' ') #=> "Hello"
# a #=> "World"
#
def first!(pattern=//)
case pattern
when Regexp, String
a = shatter(pattern) # req. scan
r = a.first
a.shift
a.shift
replace( a.join('') )
return r
else
super
end
end
# Removes the last separation from a string.
# Default seperation is by characeter.
#--
# If a zero-length record separator is supplied,
# the string is split on /\n+/. If the record
# separator is set to <tt>nil</tt>, then the
# string is split on characters.
#++
#
# a = "Hello World"
# a.last! #=> "d"
# a #=> "Hello Worl"
#
# a = "Hello World"
# a.last!(' ') #=> "World"
# a #=> "Hello"
#
def last!(pattern=//)
case pattern
when Regexp, String
a = shatter(pattern) #req. scan
r = a.last
a.pop
a.pop
replace(a.join(''))
return r
else
super
end
end
# TODO: Should Strin#first= replace first char as in Indexable?
# Prepends to a string.
#
# "Hello World".first = "Hello," #=> "Hello, Hello World"
def first=(x)
insert(0, x.to_s)
end
# Appends to a string.
#
# "Hello World".last = ", Bye." #=> "Hello World, Bye."
#
def last=(str)
self << str
end
end
|