Class: StringSnip
- Inherits:
-
Object
- Object
- StringSnip
- Defined in:
- lib/gren/common/string_snip.rb
Class Method Summary collapse
- .index_conv(str, value) ⇒ Object
- .ranges_compound(ranges) ⇒ Object
- .ranges_conv(ranges, str) ⇒ Object
- .ranges_sort(ranges) ⇒ Object
Instance Method Summary collapse
-
#initialize(size = 256, delimiter = '<<snip>>', pri = nil) ⇒ StringSnip
constructor
A new instance of StringSnip.
- #snip(str, ranges) ⇒ Object
Constructor Details
#initialize(size = 256, delimiter = '<<snip>>', pri = nil) ⇒ StringSnip
Returns a new instance of StringSnip.
4 5 6 7 8 |
# File 'lib/gren/common/string_snip.rb', line 4 def initialize(size = 256, delimiter = '<<snip>>', pri = nil) @size = size @delimiter = delimiter @pri = pri end |
Class Method Details
.index_conv(str, value) ⇒ Object
32 33 34 35 36 37 38 |
# File 'lib/gren/common/string_snip.rb', line 32 def self.index_conv(str, value) if (value < 0) str.size + value else value end end |
.ranges_compound(ranges) ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/gren/common/string_snip.rb', line 44 def self.ranges_compound(ranges) result = [] index = 0 while (ranges.size > 0) if (ranges.size > 1 && ranges[0].end + 1 >= ranges[1].begin) v1, v2 = ranges.shift(2) ranges.unshift v1.begin..((v1.end > v2.end) ? v1.end : v2.end) else result << ranges.shift end end result end |
.ranges_conv(ranges, str) ⇒ Object
28 29 30 |
# File 'lib/gren/common/string_snip.rb', line 28 def self.ranges_conv(ranges, str) ranges.map {|i| index_conv(str, i.begin)..index_conv(str, i.end)} end |
.ranges_sort(ranges) ⇒ Object
40 41 42 |
# File 'lib/gren/common/string_snip.rb', line 40 def self.ranges_sort(ranges) ranges.sort_by{|i| i.begin} end |
Instance Method Details
#snip(str, ranges) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/gren/common/string_snip.rb', line 10 def snip(str, ranges) @str = str @ranges = ranges # no snip return @str if (@str.size <= @size) # snip @ranges = StringSnip::ranges_conv(@ranges, @str) @ranges = StringSnip::ranges_sort(@ranges) @ranges = StringSnip::ranges_compound(@ranges) # result results = [] @ranges.each {|r| results << @str[r] } return results.join(@delimiter) end |