Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/abstractor/core_ext/string.rb
Instance Method Summary collapse
- #date? ⇒ Boolean
- #integer? ⇒ Boolean
- #numeric? ⇒ Boolean
-
#range(pattern, offset = 0) ⇒ Object
Like #index but returns a Range.
-
#range_all(pattern, reuse = false) ⇒ Object
Like #index_all but returns an array of Ranges.
-
#range_of_line ⇒ Object
Returns an array of ranges mapping the characters per line.
- #ssn? ⇒ Boolean
- #to_boolean ⇒ Object
Instance Method Details
#date? ⇒ Boolean
82 83 84 85 86 87 88 |
# File 'lib/abstractor/core_ext/string.rb', line 82 def date? begin d = Date.parse(self) rescue ArgumentError => e nil end end |
#integer? ⇒ Boolean
73 74 75 76 77 78 79 80 |
# File 'lib/abstractor/core_ext/string.rb', line 73 def integer? begin Integer(self) self rescue ArgumentError => e nil end end |
#numeric? ⇒ Boolean
69 70 71 |
# File 'lib/abstractor/core_ext/string.rb', line 69 def numeric? match(Regexp::NUMERIC) != nil end |
#range(pattern, offset = 0) ⇒ Object
Like #index but returns a Range.
"This is a test!".range('test') #=> (10..13)
CREDIT: Trans
19 20 21 22 23 24 25 26 27 28 |
# File 'lib/abstractor/core_ext/string.rb', line 19 def range(pattern, offset=0) unless Regexp === pattern pattern = Regexp.new(Regexp.escape(pattern.to_s)) end string = self[offset..-1] if md = pattern.match(string) return (md.begin(0)+offset)..(md.end(0)+offset-1) end nil end |
#range_all(pattern, reuse = false) ⇒ Object
Like #index_all but returns an array of Ranges.
"abc123abc123".range_all('abc') #=> [0..2, 6..8]
TODO: Add offset ?
CREDIT: Trans
38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/abstractor/core_ext/string.rb', line 38 def range_all(pattern, reuse=false) r = []; i = 0 while i < self.length rng = range(pattern, i) if rng r << rng i += reuse ? 1 : rng.end + 1 else break end end r.uniq end |
#range_of_line ⇒ Object
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
60 61 62 63 64 65 66 67 |
# File 'lib/abstractor/core_ext/string.rb', line 60 def range_of_line offset=0; charmap = [] each_line do |line| charmap << (offset..(offset + line.length - 1)) offset += line.length end charmap end |
#ssn? ⇒ Boolean
90 91 92 93 94 95 96 97 98 |
# File 'lib/abstractor/core_ext/string.rb', line 90 def ssn? if (integer? && length == 9) self elsif ((self =~ /[0-9]{3}-[0-9]{2}-[0-9]{4}/ ) == 0) self.gsub('-','') else nil end end |
#to_boolean ⇒ Object
7 8 9 10 11 |
# File 'lib/abstractor/core_ext/string.rb', line 7 def to_boolean return true if self == true || self =~ (/(true|t|yes|y|1)$/i) return false if self == false || self.blank? || self =~ (/(false|f|no|n|0)$/i) raise ArgumentError.new("invalid value for Boolean: \"#{self}\"") end |