Module: Nuggets::String::HighlightMixin
- Included in:
- String
- Defined in:
- lib/nuggets/string/highlight_mixin.rb
Instance Method Summary collapse
-
#highlight(needle, prefix = '|', postfix = prefix) ⇒ Object
call-seq: str.highlight(needle[, prefix[, postfix]]) => new_string.
Instance Method Details
#highlight(needle, prefix = '|', postfix = prefix) ⇒ Object
call-seq:
str.highlight(needle[, prefix[, postfix]]) => new_string
Highlight occurrences of needle (String(s) and/or Regexp(s))
in str by surrounding them with prefix and postfix.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/nuggets/string/highlight_mixin.rb', line 36 def highlight(needle, prefix = '|', postfix = prefix) offsets = [] Array(needle).each { |arg| while index = index(arg, index || 0) offsets << [index, index += ($& || arg).length] end } flattened = [current = offsets.sort!.shift] offsets.each { |offset| i1, j1 = current i2, j2 = offset i2 > j1 ? flattened << current = offset : j2 > j1 ? current[-1] = j2 : nil } dup.tap { |result| flattened.reverse_each { |i, j| result.insert(j, postfix).insert(i, prefix) } } end |